Loading

列表、条件渲染和事件处理

列表渲染

基本用法:

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>

条件渲染

NgIf

<p *ngIf="heroes.length > 3">There are many heroes!</p>

ngIf<ng-template>

<ng-template [ngIf]="condition"><div>...</div></ng-template>

NgSwitch

NgSwitch 的语法比较啰嗦,使用频率小一些。

<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" >

事件绑定的另一种写法,使用 on- 前缀的方式:

<!-- 绑定事件处理函数 -->
<button on-click="onSave()">On Save</button>

 

posted @ 2022-03-19 14:15  1640808365  阅读(21)  评论(0编辑  收藏  举报