列表、条件渲染和事件处理
export class AppComponent { heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado']; }
<p>Heroes:</p> <ul> <li *ngFor="let hero of heroes"> {{ hero }} </li> </ul>
也可以获取 index 索引:
<div *ngFor="let hero of heroes; let i=index">{{i + 1}} - {{hero.name}}</div>
<p *ngIf="heroes.length > 3">There are many heroes!</p>
ngIf
和 <ng-template>
<ng-template [ngIf]="condition"><div>...</div></ng-template>
<div [ngSwitch]="currentHero.emotion"> <app-happy-hero *ngSwitchCase="'happy'" [hero]="currentHero"></app-happy-hero> <app-sad-hero *ngSwitchCase="'sad'" [hero]="currentHero"></app-sad-hero> <app-confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></app-confused-hero> <app-unknown-hero *ngSwitchDefault [hero]="currentHero"></app-unknown-hero> </div>
<button (click)="onSave()">Save</button>
可以把事件对象传递到事件处理函数中:
<button (click)="onSave($event)">On Save</button>
也可以传递额外的参数(取决于你的业务):
<button (click)="onSave($event, 123)">On Save</button>
当事件处理语句比较简单的时候,我们可以内联事件处理语句:
<button (click)="message = '哈哈哈'">内联事件处理</button>
<input [value]="message" (input)="message=$event.target.value" >
<!-- 绑定事件处理函数 --> <button on-click="onSave()">On Save</button>