angular6.x中ngTemplateOutlet指令的使用示例
在使用angular進行開發(fā)的時候,通過屬性綁定向組件內(nèi)部傳值的方式,有時候并不能完全滿足需求,比如我們寫了一個公共組件,但是某個模板使用這個公共組件的時候,需要在其內(nèi)部添加一些標(biāo)簽內(nèi)容,這種情況下,除了使用ngIf/ngSwitch預(yù)先在組件內(nèi)部定義之外,就可以利用ngTemplateOutlet指令向組件傳入內(nèi)容.
ngTemplateOutlet指令類似于angularjs中的ng-transclude,vuejs中的slot.
ngTemplateOutlet是結(jié)構(gòu)型指令,需要綁定一個TemplateRef類型的實例.
使用方式如下:
@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!');
}
}
代碼中除了跟組件外定義了兩個組件
- 容器組件:app-content
- 傳遞進去的內(nèi)容組件:app-nested-component
app-content組件接收一個TemplateRef類型的輸入屬性templateRef,并在模板中將其綁定到了ngTemplateOutlet指令,當(dāng)組件接收到templateRef屬性時,就會將其渲染到ngTemplateOutlet指令所在的位置.
上例中,app-content組件templateRef屬性的來源,是在根組件的模板內(nèi),直接通過#符號獲取到了app-nested-component組件所在<ng-template>的引用并傳入的.
在實際應(yīng)用中,除了這種方式,也可以直接在組件內(nèi)部獲取TemplateRef類型的屬性并綁定到ngTemplateOutlet指令.
比如在容器組件為模態(tài)框的情況下,并不能通過模板傳值,就可以使用下面這種方式:
@ViewChild('temp') temp: TemplateRef<any>
openDialog(){
this.dialog.open(ViewDialogComponent, {data: this.temp)
}
在容器組件中還可以定義被傳遞內(nèi)容的上下文(上例app-content組件中的myContext屬性),其中的$implicit屬性作為默認(rèn)值,在被傳遞的內(nèi)容中可以以重命名的方式訪問(上例let-name),對于上下文中其他的屬性,就需要通過let-屬性名的方式訪問了.
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Angularjs+mybatis實現(xiàn)二級評論系統(tǒng)(仿簡書)
這篇文章主要為大家詳細(xì)介紹了基于Angularjs+mybatis實現(xiàn)二級評論系統(tǒng),模仿簡書效果制作,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02
總結(jié)AngularJS開發(fā)者最常犯的十個錯誤
AngularJS是如今最受歡迎的JS框架之一,簡化開發(fā)過程是它的目標(biāo)之一,這使得它非常適合于元型較小的apps的開發(fā),但也擴展到具有全部特征的客戶端應(yīng)用的開發(fā)。下面給大家總結(jié)了AngularJS開發(fā)者最常犯的十個錯誤,有需要的可以參考學(xué)習(xí)下。2016-08-08
AngularJs Understanding the Model Component
本文主要介紹AngularJs Understanding the Model Component的內(nèi)容,這里整理了相關(guān)資料,并詳細(xì)講解了這部分知識,有興趣的小伙伴可以參考下2016-09-09
Javascript基礎(chǔ)_標(biāo)記文字的實現(xiàn)方法
下面小編就為大家?guī)硪黄狫avascript基礎(chǔ)_標(biāo)記文字的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06
Web開發(fā)使用Angular實現(xiàn)用戶密碼強度判別的方法
這篇文章主要介紹了Web開發(fā)使用Angular實現(xiàn)用戶密碼強度判別的方法,需要的朋友可以參考下2017-09-09

