在 Angular 中最常用的指令分為兩種,它們分別是 屬性型指令 和 結構型指令,
NgClass
- 作用:添加或移除一組 CSS 類
NgStyle
- 作用:添加或移除一組 CSS 樣式
NgModel
- 作用:雙向系結到 HTML 表單元素
NgIf
- 作用:根據條件添加或移除 DOM
- 語法:
<div *ngIf="false">看不見我</div>
我們也可以通過類系結或樣式系結來顯示或隱藏一個元素,
<!-- isSpecial is true -->
<div [class.hidden]="!isSpecial">Show with class</div>
<div [class.hidden]="isSpecial">Hide with class</div>
<div [style.display]="isSpecial ? 'block' : 'none'">Show with style</div>
<div [style.display]="isSpecial ? 'none' : 'block'">Hide with style</div>
NgSwitch
- 作用:類似于 JavaScript 中的 switch 陳述句,根據條件渲染多個選項中的一個,
- 語法:該指令包括三個相互協作的指令:
NgSwitch、NgSwitchCase、NgSwitchDefault
<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>
NgFor
- 作用:串列渲染
- 語法:
<div *ngFor="let hero of heroes">{{hero.name}}</div>
帶索引的 *ngFor
<ul>
<li *ngFor="let item of todos; let i = index">{{ item.title + i }}</li>
</ul>
自定義指令
參考檔案:
- 屬性型指令:https://angular.io/guide/attribute-directives
- 結構型指令:https://angular.io/guide/structural-directives
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/153829.html
標籤:JavaScript
上一篇:ng--tolist說明
下一篇:ng-http
