Skip to main content

Common Syntax

Template Syntax

<h3>Current customer: {{ currentCustomer }}</h3>

<p>{{title}}</p>
<div><img alt="item" src="{{itemImageUrl}}"></div>
<button type="button" (click)="onSave($event)">Save</button>

<button type="button" *ngFor="let hero of heroes" (click)="deleteHero(hero)">{{hero.name}}</button>

<form #heroForm (ngSubmit)="onSubmit(heroForm)"> ... </form>
<img alt="item 2" [src]="itemImageUrl2">
<label for="customer-input">Type something:
<input id="customer-input" #customerInput>{{customerInput.value}}
</label>
@Component({
template: `
<ul>
<li *ngFor="let customer of customers">{{ customer.value }}</li>
</ul>
`
})
class AppComponent {
customers = [{value: 'Ebony'}, {value: 'Chiho'}];
}

Attribute Binding

<p [attr.attribute-you-are-targeting]="expression"></p>
<!-- create and set an aria attribute for assistive technology -->
<button type="button" [attr.aria-label]="actionName">{{actionName}} with Aria</button>
<!--  Attribute expression calculates colspan=2 -->
<tr><td [attr.colspan]="1 + 1">One-Two</td></tr>

<!-- Notice the colSpan property is camel case -->
<tr><td [colSpan]="1 + 1">Three-Four</td></tr>

Sometimes there are differences between the name of property and an attribute.

  • colspan is an attribute of <td>, while colSpan with a capital "S" is a property.
  • When using attribute binding, use colspan with a lowercase "s".

Class and Style Binding

[class.sale]="onSale"
[class]="classExpression"

The expression can be one of:

  • A space-delimited string of class names.
  • An object with class names as the keys and truthy or falsy expressions as the values.
  • An array of class names.
<nav [style.background-color]="expression"></nav>
<nav [style.backgroundColor]="expression"></nav>
@Component({
selector: 'app-nav-bar',
template: `
<nav [style]='navStyle'>
<a [style.text-decoration]="activeLinkStyle">Home Page</a>
<a [style.text-decoration]="linkStyle">Login</a>
</nav>`
})
export class NavBarComponent {
navStyle = 'font-size: 1.2rem; color: cornflowerblue;';
linkStyle = 'underline';
activeLinkStyle = 'overline';
/* . . . */
}

Conditionals

These are Angular structural directives used for conditional rendering.

ngIf

Use ngIf for conditional rendering or apply CSS classes or style to adjust the display of certain elements. There is no AngularJS equivalent of ng-show or ng-hide.

<p *ngIf="showMessage">Show this message when boolean variable is truthy</p>

ngSwitch, ngSwitchCase

<container-element [ngSwitch]="switch_expression">
<some-element *ngSwitchCase="match_expression_1">...</some-element>
<some-element *ngSwitchCase="match_expression_2">...</some-element>
<some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
<ng-container *ngSwitchCase="match_expression_3">
<!-- use a ng-container to group multiple root nodes -->
<inner-element></inner-element>
<inner-other-element></inner-other-element>
</ng-container>
<some-element *ngSwitchDefault>...</some-element>
</container-element>

Containers and Templates

ngContainer

The <ng-container> allows us to use structural directives without any extra element, making sure that the only DOM changes being applied are those dictated by the directives themselves.

<ng-container *ngIf="condition">

</ng-container>
<ng-container *ngIf="condition; else templateA">

</ng-container>
<ng-template #templateA>

</ng-template>

Multiple Structural Containers

https://angular.io/api/core/ng-container#combination-of-multiple-structural-directives

https://angular-training-guide.rangle.io/directives/structural_directives/using_multiple_structural_directives

<ul>
<ng-container *ngFor="let item of items">
<li *ngIf="item.isValid">
{{ item.name }}
</li>
</ng-container>
</ul>

Event Binding

<button (click)="onSave()">Save</button>
<input (keydown.shift.t)="onKeydown($event)" />

Plurals

Use the ngPlural directive to render plural variations for an element.

<some-element [ngPlural]="value">
<ng-template ngPluralCase="=0">there is nothing</ng-template>
<ng-template ngPluralCase="=1">there is one</ng-template>
<ng-template ngPluralCase="few">there are a few</ng-template>
</some-element>

Property Binding

<!-- Notice the colSpan property is camel case -->
<tr><td [colSpan]="1 + 1">Three-Four</td></tr>
<!-- Bind button disabled state to `isUnchanged` property -->
<button type="button" [disabled]="isUnchanged">Disabled Button</button>
<p [ngClass]="classes">[ngClass] binding to the classes property making this blue</p>
<app-item-detail [childItem]="parentItem"></app-item-detail>

Repeaters

ngFor, ngForOf

ngFor and ngForOf directives are used together to render a group of items, such as a list.

<div *ngFor="let item of items"></div>

<!-- Is equivalent to ... -->

<template ngFor let-item="$implicit" [ngForOf]="items">
<div>...</div>
</template>

The following exported values can be aliased to local variables:

  • $implicit: T: The value of the individual items in the iterable (ngForOf).
  • ngForOf: NgIterable<T>: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (userStreams | async).
  • index: number: The index of the current item in the iterable.
  • count: number: The length of the iterable.
  • first: boolean: True when the item is the first item in the iterable.
  • last: boolean: True when the item is the last item in the iterable.
  • even: boolean: True when the item has an even index in the iterable.
  • odd: boolean: True when the item has an odd index in the iterable.
<li *ngFor="let user of users; index as i; first as isFirst">
{{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span>
</li>
<li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>
<button type="button" *ngFor="let hero of heroes" (click)="deleteHero(hero)">{{hero.name}}</button>
@Component({
template: `
<ul>
<li *ngFor="let customer of customers">{{ customer.value }}</li>
</ul>
`
})
class AppComponent {
customers = [{value: 'Ebony'}, {value: 'Chiho'}];
}

Lifecycle Hooks

https://angular.io/guide/glossary#lifecycle-hook

HOOK METHODDETAILS
ngOnChangesWhen an input or output binding value changes.
ngOnInitAfter the first ngOnChanges.
ngDoCheckDeveloper's custom change detection.
ngAfterContentInitAfter component content initialized.
ngAfterContentCheckedAfter every check of component content. Called once after ngAfterContentInit and every time after ngDoCheck.
ngAfterViewInitAfter the views of a component are initialized.
ngAfterViewCheckedAfter every check of the views of a component. Called once after ngAfterViewInit and every time after ngDoCheck.
ngOnDestroyJust before the directive is destroyed.

OnInit

A lifecycle hook that is called after Angular has initialized all data-bound properties of a directive. Define an ngOnInit() method to handle any additional initialization tasks.

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
ngOnInit() {
// ...
}
}

OnDestroy

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
ngOnDestroy() {
// ...
}
}

OnChanges

A callback method that is invoked immediately after the default change detector has checked data-bound properties if at least one has changed, and before the view and content children are checked.

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
@Input() prop: number = 0;

ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}

Sample File Shells

Component

https://angular.io/guide/component-overview

A component can be defined in a single .ts file or split up into .ts, .scss, and .html files.

Single file

  • src/app/components/example.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
//import { ExampleService } from '../services/example.service';

@Component({
selector: 'app-example',
template: `
<h1>Hello World!</h1>
<p>This template definition spans multiple lines.</p>
`,
styles: ['h1 { font-weight: normal; }']
})
export class ExampleComponent implements OnInit, OnDestroy {

constructor (/*private exampleService: ExampleService*/) { }

ngOnInit() {}
ngOnDestroy() {}
}

Multiple files

  • src/app/components/example.component.html
  • src/app/components/example.component.scss
  • src/app/components/example.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
//import { ExampleService } from '../services/example.service';

@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: [ './example.component.scss' ]
})
export class ExampleComponent implements OnInit, OnDestroy {

constructor (/*private exampleService: ExampleService*/) { }

ngOnInit() {}
ngOnDestroy() {}
}

Directive

Attribute Directive

import { Directive } from '@angular/core';

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {

}

Apply the directive...

<p appHighlight>Highlight me!</p>

Service

https://angular.io/guide/creating-injectable-service

src/app/services/example.service.ts

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root',
})
export class ExampleService {
getSomething() { return ""; }
}