Skip to content

Angular Directives

Note

Classes that add additional behavior to an element

NgClass

Note

Adds and removes CSS classes on an HTML element.

...
export class ngClassComponent {
    this.isSpecial = true;
}
<div [ngClass]="isSpecial ? 'special' : ''">
    This div is special
</div>

NgStyle

Note

Adds and removes styles inline on an HTML element.

...
export class ngStyleComponent {
    this.currentSyles = {
            'font-style' : this.canSave   ? 'italic' : 'normal',
            'font-weight': this.isSpecial ? 'bold'   : 'normal'
    };
}
<div [ngStyle]="currentStyles">
    This div is special
</div>

NgModel

Note

Displays and updates the properties of a data-bound object.

import { FormsModule } from '@angular/forms';
...
imports: [
    BrowserModule,
    FormsModule // <--- import into the NgModule
],
...
<label for="example-ngModel">
    [(ngModel)]:
</label>
<input
    [(ngModel)]="currentItem.name"
    (ngModelChange)="setUppercaseName($event)"
    id="example-ngModel"
>

Structural Directives

Note

Shape and reshape the DOM's structure, by adding, removing, and manipulating elements.

NgIf

<app-item-detail *ngIf="isActive" [item]="item"> </app-item-detail>

<div *ngIf="nullCustomer">Hello, <span>{{nullCustomer}}</span></div>

NgFor

<div *ngFor="let item of items">{{item.name}}</div>
<app-item-detail *ngFor="let item of items" [item]="item"></app-item-detail>

<!-- with index -->
<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>

NgSwitch

<div [ngSwitch]="currentItem.feature">
    <app-stout-item
        *ngSwitchCase="'stout'"
        [item]="currentItem"
    ></app-stout-item>
    <app-device-item
        *ngSwitchCase="'slim'"
        [item]="currentItem"
    ></app-device-item>
    <app-lost-item
        *ngSwitchCase="'vintage'"
        [item]="currentItem"
    ></app-lost-item>
</div>