Structural Directives

  • Change the DOM layout by adding or removing DOM elements.

Built-in Structural Directives

DirectivesDetails

ngFor

Repeat a node for each item in a list.

ngIf

Conditionally creates or disposes of subviews from the template.

ngSwitch

A set of directives that switch among alternative views.

ngFor

<div *ngFor="let item of items">{{item.name}}</div>
  • repeating a component view

<app-item-detail *ngFor="let item of items" [item]="item"></app-item-detail>

ngIf

  • When NgIf is false, Angular removes an element and its descendants from the DOM. Angular then disposes of their components, which frees up memory and resources.

<app-item-detail *ngIf="isActive" [item]="item"></app-item-detail>
  • guarding against null

<div *ngIf="currentCustomer">Hello, {{currentCustomer.name}}</div>

ngSwitch

DirectivesDetails

ngSwitch

An attribute directive that changes the behavior of its companion directives.

ngSwitchCase

Structural directive that adds its element to the DOM when its bound value equals the switch value and removes its bound value when it doesn't equal the switch value.

ngSwitchDefault

Structural directive that adds its element to the DOM when there is no selected ngSwitchCase.

<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>
  <app-best-item *ngSwitchCase="'bright'" [item]="currentItem"></app-best-item>
<!-- . . . -->
  <app-unknown-item *ngSwitchDefault [item]="currentItem"></app-unknown-item>
</div>

Last updated