在使用angular進行開發的時候,經過屬性綁定向組件內部傳值的方式,有時候並不能徹底知足需求,好比咱們寫了一個公共組件,可是某個模板使用這個公共組件的時候,須要在其內部添加一些標籤內容,這種狀況下,除了使用ngIf
/ngSwitch
預先在組件內部定義以外,就能夠利用ngTemplateOutlet
指令向組件傳入內容.vue
ngTemplateOutlet
指令相似於angularjs中的ng-transclude
,vuejs中的slot
.angularjs
ngTemplateOutlet
是結構型指令,須要綁定一個TemplateRef
類型的實例.app
使用方式以下:this
@Component({ selector: 'app', template: ` <h1>Angular's template outlet and lifecycle example</h1> <app-content [templateRef]="nestedComponentRef"></app-content> <ng-template #nestedComponentRef let-name> <span>Hello {{name}}!</span> <app-nested-component></app-nested-component> </ng-template> `, }) export class App {} @Component({ selector: 'app-content', template: ` <button (click)="display = !display">Toggle content</button> <template *ngIf="display" *ngTemplateOutlet="templateRef context: myContext"> </template> `, }) export class Content { display = false; @Input() templateRef: TemplateRef; myContext = {$implicit: 'World', localSk: 'Svet'}; } @Component({ selector: 'app-nested-component', template: ` <b>Hello World!</b> `, }) export class NestedComponent implements OnDestroy, OnInit { ngOnInit() { alert('app-nested-component initialized!'); } ngOnDestroy() { alert('app-nested-component destroyed!'); } }
代碼中除了根組件外定義了兩個組件spa
app-content
app-nested-component
app-content
組件接收一個TemplateRef
類型的輸入屬性templateRef
,並在模板中將其綁定到了ngTemplateOutlet
指令,當組件接收到templateRef
屬性時,就會將其渲染到ngTemplateOutlet
指令所在的位置.code
上例中,app-content
組件templateRef
屬性的來源,是在根組件的模板內,直接經過#
符號獲取到了app-nested-component
組件所在<ng-template>
的引用並傳入的.component
在實際應用中,除了這種方式,也能夠直接在組件內部獲取TemplateRef
類型的屬性並綁定到ngTemplateOutlet
指令.ci
好比在容器組件爲模態框的狀況下,並不能經過模板傳值,就能夠使用下面這種方式:開發
@ViewChild('temp') temp: TemplateRef<any> openDialog(){ this.dialog.open(ViewDialogComponent, {data: this.temp) }
在容器組件中還能夠定義被傳遞內容的上下文(上例app-content
組件中的myContext
屬性),其中的$implicit
屬性做爲默認值,在被傳遞的內容中能夠以重命名的方式訪問(上例let-name
),對於上下文中其餘的屬性,就須要經過let-屬性名
的方式訪問了.it