Structural Directive

  • Handles how a component or native elements renders using <template> tag

  • Special Syntax *myDirective

      <p *myDirective="expression">Hello</p>
    
      // same as
    
      <template [myDirective] = "expression">
          <p>Hello</p>
      </template>
  • Built-in structural directives NgIf, NgFor, NgSwitch

  • Can not apply multiple strutural directive on same element

      // wrong , will not work
      <p *ngFor="" *ngIf=""></p>

ngIf

  • Remove or Recrete a portion of DOM tree

  • Be aware of the cost of creating/destroying DOM elements

<p ngIf="exists">Lorem ipsum dolor sit.</p>

ngFor

<ul>
    <li *ngFor="let item of list; let i = index;let isOdd=odd" [ngClass]="{odd: isOdd}">
        {{ "Index"+ i}} - {{ item }}
    </li>
</ul>

ngSwitch

Behaves like ngIf syntax similar to switch

<div [ngSwitch]="tab">
    <div *ngSwitchCase="1">Lorem ipsum dolor sit.</div>
    <div *ngSwitchCase="2">Lorem ipsum dolor sit.</div>
    <div *ngSwitchDefault>Lorem ipsum dolor sit.</div>
</div>

Last updated

Was this helpful?