ng-content指令可以在組件中嵌入模板代碼,方便定制可復用的組件。
比如:頁面的header是個通用組件,導航菜單樣式已經設定好,只需在header標簽內加上菜單內容。
源碼以前文為基礎。
父組件使用方法:
<app-header #header [title]="title" name="{{name}}" (checkEmitter)="onCheckedChange($event)" > <menu> <ul> <li>aa</li> <li>bb</li> <li>cc</li> </ul> </menu> </app-header> <app-header #header2 [title]="title2" name="{{name}}" (checkEmitter)="onCheckedChange($event)" ></app-header> <button (click)="header.toggle()">通過本地變量調用子組件方法</button> <button (click)="headerToggle()">通過ViewChild調用子組件方法</button>
這樣的結構可謂清晰明了。這里只為演示ng-content的功能,如果是真正開發過程中,可以定制li
成一個菜單按鈕,更清晰。
header組件的模板:
<p> {{title}} </p> <p><input type="checkbox" name="cb" [(ngModel)]="isChecked" (click)="toggle()" />Checkbox <br /></p> <ng-content select="menu"></ng-content>
用ng-content標簽,將父組件模板中包含的menu標簽內容加到指定位置。select屬性支持css選擇器,如:"#id",".class","[name=value]"等