Structural Directives
Structural directives 使得我們可以操作整個 DOM tree, 而非只是元素本身(e.g. 依條件植入或移除整塊 div)
基本上 NgIf, NgFor, NgSwitch 應該就可以處理大部份需要 structural directives 的情境
不過既然要學習,還是建一個 attribute directive 來玩玩,這個 directive 會延遲元件的顯示
ng g d directives/delay
接著實作 delay.directive.ts 的內容如下:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[delay]'
})
export class DelayDirective {
@Input() set delay(ms: number) {
setTimeout(() => {
this.viewContainer.createEmbeddedView(this.templateRef);
}, ms);
}
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) { }
}
在使用 structural directive, 必須加上 *(星號), 像是 *ngIf, *ngFor, and ... *delay="1000"
定義好 Directive,來調整一下 DashboardComponent 的 template 如下:
<div class="mdl-cell mdl-cell--3-col" *ngFor="let stock of stocks;index as i">
<summary [stock]="stock" *delay="i * 100" cardTone></summary>
</div>
Structural directives 很不一樣
小結: