1.13.4. fejezet, Direktívák

Direktíva típusok

  • Component directive (minden Angular Component egy direktíva egy template-el)
  • Structural directive (DOM szerkezet megváltoztatására. Pl.: ngIf / ngSwitch / ngFor avagy újabban @If / @Switch / @For)
  • Attribute directive (Megjelenést alakító direktívás. Pl.: ngClass / ngStyle)
  • Custom directive (egyedi direktíva)

Structural directives

@if

<p *ngIf="isActive">Profile e-mail: {{userProfile?.email}}</p>
 
@if(isActive) {<p>Profile id: {{userProfile?.id}}</p>}
@else if (userName == 'Manager Zotya') {<p>Hi manager</p>} 
@else {<p>Not active</p>}

NgTemplate

<ng-template #emailTemplate>
  <p>Entered e-mail: {{email}}</p>
</ng-template>
 
<p *ngIf="isActive else emailTemplate">Profile e-mail: {{userProfile?.email}}</p>
 
@if(isActive) {<p>Profile id: {{userProfile?.id}}</p>} @else {
  <ng-container [ngTemplateOutlet]="emailTemplate"></ng-container>
}

@switch

<div [ngSwitch]="userRole">
  <p *ngSwitchCase="'user'">Welcome User</p>
  <p *ngSwitchCase="'manager'">Welcome Manager</p>
  <p *ngSwitchDefault>Welcome somebody else</p>
</div>
 
@switch (keycloak.getUserRoles().indexOf('user')) {
  @case (0) {
    <p>User role active</p>
  }
  @case (1) {
    <p>User subrole active</p>
  }
  @default {
    <p>Somebody else active</p>
  }
}

@for

<ul>
  <li *ngFor="let item of users; let i = index">{{i}}. {{item}}</li>
</ul>
 
<ul>
@for(item of users; track item; let i = $index; let count = $count; let odd = $odd) {
  <li [style.background-color]="(odd?'gray':'white')" [style.color]="odd?'white':'black'">{{count - i}}. {{item}} <button (click)="deleteUser(i)">Delete</button></li>
} @empty {
  <li>Empty list</li>
}
</ul>
 
// home.component.ts
  deleteUser(i:number) {
    this.users.splice(i,1);
  }

Attribute directives

ngStyle

<h1 [ngStyle]="{
  'color':isActive?'lime':'red',
  'textTransform':isActive?'uppercase':'lowercase',
}">LoggedIn</h1>

ngClass

<h1 [class.loggedIn]="isActive"  [class.loggedOut]="!isActive">LoggedIn</h1>
 
<h1 [ngClass]="isActive?'loggedIn':'loggedOut'">LoggedIn</h1>
<h1 [ngClass]="{'loggedIn':isActive,'loggedOut':!isActive}">LoggedIn</h1>