Angular學習筆記(十六)元件週期鉤子之投影和AfterContentInit
阿新 • • 發佈:2019-02-11
投影
定義:在執行時動態改變模版內容,父元件主動控制子元件的顯示內容。
指令:ng-content
方法:在html中,父元件中引用子元件標籤的寫入要顯示的內容,子元件使用<ng-content></ng-content>
確定投影點。
多個投影點標識:
<ng-content select=".blue"></ng-content>
匹配class名為blue的顯示內容
<ng-content select="header"></ng-content>
匹配header標籤的顯示內容
<ng-content select="[name]=red"></ng-content>
demo:
app.component.html
<app-aftercontent>
<span style="color:red;">我是要投影的內容</span>
</app-aftercontent>
aftercontent.component.html
<p>
aftercontent works!
<ng-content></ng-content>
</p>
執行圖:
多個投影點demo:
app.component.html
<app-aftercontent>
<div style="color:red;" class="red">我是要投影的內容1</div>
<p>我是要投影的內容2</p>
<div style="color:yellow;" name="yellow">我是要投影的內容3</div>
</app-aftercontent>
aftercontent.component.html
<p>
aftercontent works!
<ng-content select=".red"></ng-content>
<ng-content select="p"></ng-content>
<ng-content select="[name=yellow]"></ng-content>
</p>
執行圖
AfterContentInit
定義:投影內容初始化,發生在doCheck之後,只調用一次
AfterContentCheck
定義:投影內容變更檢測,發生在AfterContentInit之後,可重複呼叫
要點:父元件的投影鉤子在子元件之前,父元件投影鉤子初始化和檢測完畢,才呼叫子元件投影鉤子。可以理解為:因為是要把父元件的內容投影進子元件,所以父元件鉤子先執行。
demo:
app.component.ts
export class AppComponent implements AfterContentInit,AfterContentChecked {
ngAfterContentInit():void{
console.log('父元件投影內容初始化完畢');
}
ngAfterContentChecked():void{
console.log('父元件投影內容變更檢測完畢');
}
}
aftercontent.component.ts
export class AftercontentComponent implements OnInit,AfterContentInit,AfterContentChecked {
constructor() { }
ngOnInit() {
}
ngAfterContentInit():void{
console.log('子元件投影內容初始化完畢');
}
ngAfterContentChecked():void{
console.log('子元件投影內容變更檢測完畢');
}
}
Tips:
控制檯在Angular專案running後會再次執行變更檢測鉤子,如ngDoCheck、ngAfterContentChecked、ngAfterViewChecked