Angular

Note for Angular.io (Angular)

Architecture overview

The basic building blocks of Angular 2 applications

Modules

Angular has its modularity system called Angular modules or NgModules.

Every Angular app has at least one module, the root module, conventionally named AppModule.

maybe root module be the only module in the small application, or many more feature modules in most apps.

Angular module is a class with an @NgModule decorator.

NgModule properties
|—->declarations: [‘view classes, eg. components, directives and pipes’].
|—->exports: the subset of declarations that should be visible and usable in the component templates of the modules.
|—->imports: other modules whose exported classes are needed by component templates declared in this module.
|—->providers: services
|—->bootstrap: the main application view, called the root component, that hosts all other app views.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [ BrowserModule ],
providers: [ Logger ],
declarations: [ AppComponent ],
exports: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Launch an application by bootstrapping its root module. During development you’re likely to bootstrap the AppModule in a main.ts file like this one.

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

Angular libraries

Angular ships as a collection of JavaScript modules. You can think of them as library modules.

Each Angular library name begins with the @angular prefix.

You install them with the npm package manager and import parts of them with JavaScript import statements.

Components

A component controls a patch of screen called a view.

You define a component’s application logic - what it does to support the view - inside a class.

The class interacts with the view through an API of properties and methods.

export class HeroListComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;

constructor(private service: HeroService) { }

ngOnInit() {
this.heroes = this.service.getHeroes();
}

selectHero(hero: Hero) { this.selectedHero = hero; }
}

Templates

You define a component’s view with its companion template.

<h2>Hero List</h2>
<p><i>Pick a hero from the list</i></p>
<ul>
<li *ngFor="let hero of heroes" (click)="selectHero(hero)">
{{hero.name}}
</li>
</ul>
<hero-detail *ngIf="selectedHero" [hero]="selectedHero"></hero-detail>

Metadata

Metadata tells Angular how to process a class.

Attaching metadata to the class to tell Angular that a class is a component.

In TypeScript, you attach metadata by using a decorator.

@Component({
selector: 'hero-list',
templateUrl: 'app/hero-list.component.html',
providers: [ HeroService ]
})
export class HeroListComponent implements OnInit {
/* . . . */
}

@Component properties:
|—->selector: CSS selector.
|—->templateUrl: address of this component’s HTML template.
|—->directives: array of the components or directives that this template requires.
|—->providers: array of dependency injection providersfor the services that the component requires.

Data binding

Angular supports data binding,

databinding

4 forms of data binding syntax.

<li>{{hero.name}}</li>
<hero-detail [hero]="selectedHero"></hero-detail>
<li (click)="selectHero(hero)"></li>
  • The interpolation display the component’s hero.name property value within the <li> tags.
  • The [hero] property binding passes the value of selectedHero from the parent HeroListComponent to the hero property of the child HeroDetailComponent.
  • The (click) event binding calls the component’s selelctHero method when the user clicks a hero’s name.
<input [(ngModel)]="hero.name">
  • Two-way data binding
    Combines property and event binding in a single notation, using the ngModel.

Angular processes all data bindings once per JavaScript event cycle, from the root of the application component tree through all child components.

component-databinding

parent-child-binding

Directives

Angular templates are dynamic.
When Angular renders them, it transforms the DOM according to the instructions given by directives.

@Directive

A component is a directive-with-a-template;
A @Component decorator is actually a @Directive decorator extended with template-oriented features.

While a component is technically a directive, components are so distinctive and central to Angular applications that
this architectual overview separates components from directives.

structural directive attribute directive

Structural directives alter layout by adding, removing, and replacing elements in DOM.

<li *ngFor="let hero of heroes"></li>
<hero-detail *ngIf="selectedHero"></hero-detail>

Attribute directives alter the appearance or behavior of an existing element.
In templates they look like regular HTML attributes, hence the name.

E.g. ngModel
ngModel modifies the behavior of an existing element (typically an <input> tag) by setting its display value property and responding to change events.

<input [(ngModel)]="hero.name">

Angular has a few more directives that either alter the layout structure (for example, ngSwitch) or modify aspects of DOM elements and components (for example, ngStyle and ngClass).

Then create your own directives.

Services

Service is a broad category encompassing any value, function, or feature that your application needs.

A service is typically a class with a narrow, well-defined purpose.

export class Logger {
log(msg: any) { console.log(msg); }
error(msg: any) { console.error(msg); }
warn(msg: any) { console.warn(msg); }
}
export class HeroService {
private heros: Hero[] = [];

constructor(
private backend: BackendService,
private logger: Logger
) {}


getHeroes() {
this.backend.getAll(Hero).then((heroes: Hero[]) => {
this.logger.log(`Fetched ${heroes.length} heroes.`);
this.heroes.push(...heroes); // fill cache
});

return this.heroes;
}
}

Dependency Injection

Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires.
Most dependencies are services.
Angular uses dependency injection to provide new components with the services they need.

constructor(private service: HeroService) {}

When Angular creates a component, it first asks an injector for the services that the component requires.

An injector maintains a container of service instances that it has previously created.
if a requested service instance is not in the container, the injector makes one and adds it to the container before returning the service to angular.
When all requested services have been resolved and returned, Angular can call the component’s constructor with those services as arguments.
This is dependency injection.

If the injector doesn’t have a HeroService, how does it know how to make one ?

In brief, you must have previously registered a provider of the HeroService with the injector.

  • Register providers in modules.

Add providers to the root module so that the same instance of a service is avaiable everywhere.

providers: [
BackendService,
HeroService,
Logger
]

  • Register providers in component.
@Component({
selector: 'hero-list',
templateUrl: 'app/hero-list.component.html',
providers: [HeroService]
})

Registering at a component level means you get a new instance of the service with each new instance of that component.

  • Dependency injection is wired into the Angular framework and used everywhere.

  • The injector is the main mechanism.

    • An injector maintains a container of service instances that it created.
    • An injector can create a new service instance from a provider.
  • A provider is a recipe for creating a service.

  • Register providers with injectors.

More

Here is a brief, alphabetical list of other important Angular features and services. Most of them are covered in this documentation (or soon will be).

  • Animations: Animate component behavior without deep knowledge of animation techniques or CSS with Angular’s animation library.

  • Change detection: The change detection documentation will cover how Angular decides that a component property value has changed, when to update the screen, and how it uses zones to intercept asynchronous activity and run its change detection strategies.

  • Events: The events documentation will cover how to use components and services to raise events with mechanisms for publishing and subscribing to events.

  • Forms: Support complex data entry scenarios with HTML-based validation and dirty checking.

  • HTTP: Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.

  • Lifecycle hooks: Tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the lifecycle hook interfaces.

  • Pipes: Use pipes in your templates to improve the user experience by transforming values for display. Consider this currency pipe expression:

price | currency:'USD':true

It displays a price of “42.33” as $42.33.

  • Router: Navigate from page to page within the client application and never leave the browser.

  • Testing: Run unit tests with Angular’s testing library on your application parts as they interact with the Angular framework.

Template Syntax

HTML

Template expressions

A template expression produces a value. Angular executes the expression and assigns it to a property of a binding target;

the target might be

  • an HTML element
  • a component
  • a directive.
  1. interpolation - <div></div>
  2. property binding - [property]="expression"

We write template expressions in a language that looks like JavaScript. Many JavaScript expressions are legal template expressions, but not all.

JavaScript expressions that have or promote side effects are prohibited, including:

  • assignments (=, +=, -=, …)
  • new
  • chaining expressions with ; or ,
  • increment and decrement operators (++ and —)

Other notable differences from JavaScript syntax include:

  • no support for the bitwise operators | and &
  • new template expression operators, such as | and ?.

Expression context

The expression context is typically the component instance, which is the source of binding values.

The component itself is usually the expression context, in which case the template expression usually references that component.

The expression context can include objects other than the component. A template reference variable is one such alternative context object.

Expression guidelines

NO VISIBLE SIDE EFFECTS

A template expression should not change any application state other than the value of the target property.

This rule is essential to Angular’s “unidirectional data flow” policy.

We should never worry that reading a component value might change some other displayed value.

The view should be stable throughout a single rendering pass.

QUICK EXECUTION

Expressions should finish quickly or the user experience may drag, especially on slower devices.

SIMPLICITY

A property name or method call should be the norm. An occasional Boolean negation (!) is OK. Otherwise, confine application and business logic to the component itself, where it will be easier to develop and test.

IDEMPOTENCE

In Angular terms, an idempotent expression always returns exactly the same thing until one of its dependent values changes.

Template statements

A template statement responds to an event raised by a binding target such as an element, component, or directive.

(event)="statement"

A template statement has a side effect. It’s how we update application state from user input. There would be no point to responding to an event otherwise.

Responding to events is the other side of Angular’s “unidirectional data flow”. We’re free to change anything, anywhere, during this turn of the event loop.

Like template expressions, template statements use a language that looks like JavaScript.

The template statement parser is different than the template expression parser and specifically supports both basic assignment (=) and chaining expressions (with ; or ,).

certain JavaScript syntax is not allowed:

  • new
  • increment and decrement operators, ++ and —
  • operator assignment, such as += and -=
  • the bitwise operators | and &
  • the template expression operators

Statement context

As with expressions, statements can refer only to what’s in the statement context — typically the component instance to which we’re binding the event.

The onSave in (click)="onSave()" is sure to be a method of the data-bound component instance.

The statement context may include an object other than the component. A template reference variable is one such alternative context object. We’ll frequently see the reserved $event symbol in event binding statements, representing the “message” or “payload” of the raised event.

Statement guidelines

As with expressions, avoid writing complex template statements. A method call or simple property assignment should be the norm.

Binding Syntax

Data direction Syntax Binding type
One-way from data source to view target \{\{expressions\}\} Interpolation
[target]="expression" Property
bind-target = "expression" Attribute
Class
Style
One-way from view target to data source (target)="statement" Event
on-target="statement"
Two-way [(target)]="expression" Two-way
bindon-target="expression"

A new mental model

HTML attribute vs. DOM property

The distinction between an HTML attribute and a DOM property is crucial to understanding how Angular binding works.

Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).

  • A few HTML attributes have 1:1 mapping to properties. id is one example.
  • Some HTML attributes don’t have corresponding properties. colspan is one example.
  • Some DOM properties don’t have corresponding attributes. textContent is one example.
  • Many HTML attributes appear to map to properties … but not in the way we might think!

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can’t.

The HTML attribute and the DOM property are not the same thing, even when they have the same name.

Template binding works with properties and events, not attributes.

In the world of Angular, the only role of attributes is to initialize element and directive state. When we data bind, we’re dealing exclusively with element and directive properties and events. Attributes effectively disappear.

Binding targets

The target of a data binding is something in the DOM.

Depending on the binding type, the target can be

  • an (element | component | directive) property
  • an (element | component | directive) event
  • an attribute name.
Binding Type Target Examples
Property Element roperty <img [src]="heroImageUrl">
Component property <hero-detail [hero]="currentHero"></hero-detail>
Directive property <div [ngClass]="{selected:isSelected}"></div>
Event Element event <button (click)="onSave()">Save</button>
Component event <hero-detail (deleteRequest)="deleteHero()"></hero-detail>
Directive event <div (myClick)="clicked=$event">click me</div>
Two-way Event and property <input [(ngModel)]="heroName">
Attribute Attribute(the exception) <button [attr.aria-label]="help">help</button>
Class class property <div [class.special]="isSpecial">Special</div>
Sytle style property <button [style.color] = "isSpecial ? 'red' : 'green'">

Property binding

Attribute, class, and style bindings

Event binding

Two-way data binding with NgModel

Built-in directives

NgClass

NgStyle

NgIf

NgSwitch

NgFor