Angular Directive adalah attribut yang dimasukkan dalam kod HTML kita, bagi menjadikan ia lebih dinamik. Ia hampir sama seperti server side script, cuma ia berlaku pada client side. Ia ada if, switch, style, class, for, dan nonBindable.
Ng If
<div *ngIf="false" style="text-align:center"> <h1> Welcome to {{title}}! </h1> </div>
<div *ngIf="a > b" style="text-align:center"> <h1> Welcome to {{title}}! </h1> </div>
<div *ngIf="string == 'yesza'" style="text-align:center"> <h1> Welcome to {{title}}! </h1> </div>
<div *ngIf="show()" style="text-align:center"> <h1> Welcome to {{title}}! </h1> </div>
//app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; a = 3; b = 2; string = "yesza"; show(){ return false; } }
Ng Switch
<div class="container"> <div *ngIf="myVar == 'A'">Var is A</div> <div *ngIf="myVar == 'B'">Var is B</div> <div *ngIf="myVar != 'A' && myVar != 'B'">Var is something else</div> </div>
<div class="container" [ngSwitch]="myVar"> <div *ngSwitchCase="'A'">Var is A</div> <div *ngSwitchCase="'B'">Var is B</div> <div *ngSwitchDefault>Var is something else</div> </div>
Value is {{ choice }} <div class="container" [ngSwitch]="choice"> <div *ngSwitchCase="1">Var is A</div> <div *ngSwitchCase="2">Var is B</div> <div *ngSwitchDefault>Var is something else</div> </div> <button class="btn btn-primary" (click)="next()">Next Choice</button>
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; a = 3; b = 2; string = "yesza"; myVar = "B"; choice=1; show(){ return false; } next(){ if(this.choice < 5) this.choice++; else this.choice=1; } }
ngStyle
<div [ngStyle]="{color: 'white', 'background-color': 'blue'}"> Uses fixed white text on blue background </div>
<div class="ui input"> <input type="text" name="color" value="{{color}}" #colorinput> </div> <div class="ui input"> <input type="text" name="fontSize" value="{{fontSize}}" #fontinput> </div> <button class="ui primary button" (click)="apply(colorinput.value, fontinput.val\ ue)"> Apply settings </button>
ngClass
ngFor
<h4 class="ui horizontal divider header"> Nested data </h4> <div *ngFor="let item of peopleByCity"> <h2 class="ui header">{{ item.city }}</h2> <table class="ui celled table"> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tr *ngFor="let p of item.people"> <td>{{ p.name }}</td> <td>{{ p.age }}</td> </tr> </table> </div>
this.peopleByCity = [ { city: 'Miami', people: [ ] }, { name: { name: 'John', age: 12 }, 'Angel', age: 22 } { city: 'Sao Paulo', people: [ { name: 'Anderson', age: 35 }, { name: 'Felipe', age: 36 } ] } ]; }
ngNonBindable