angular6.x中ngTemplateOutlet指令的使用示例
在使用angular進行開發(fā)的時候,通過屬性綁定向組件內(nèi)部傳值的方式,有時候并不能完全滿足需求,比如我們寫了一個公共組件,但是某個模板使用這個公共組件的時候,需要在其內(nèi)部添加一些標簽內(nèi)容,這種情況下,除了使用ngIf/ngSwitch預先在組件內(nèi)部定義之外,就可以利用ngTemplateOutlet指令向組件傳入內(nèi)容.
ngTemplateOutlet指令類似于angularjs中的ng-transclude,vuejs中的slot.
ngTemplateOutlet是結構型指令,需要綁定一個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指令,當組件接收到templateRef屬性時,就會將其渲染到ngTemplateOutlet指令所在的位置.
上例中,app-content組件templateRef屬性的來源,是在根組件的模板內(nèi),直接通過#符號獲取到了app-nested-component組件所在<ng-template>的引用并傳入的.
在實際應用中,除了這種方式,也可以直接在組件內(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屬性作為默認值,在被傳遞的內(nèi)容中可以以重命名的方式訪問(上例let-name),對于上下文中其他的屬性,就需要通過let-屬性名的方式訪問了.
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
AngularJS與BootStrap模仿百度分頁的示例代碼
分頁在很多時候都能用到,這篇文章主要介紹了AngularJS與BootStrap模仿百度分頁的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05angularJs中json數(shù)據(jù)轉換與本地存儲的實例
今天小編就為大家分享一篇angularJs中json數(shù)據(jù)轉換與本地存儲的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10angularJs select綁定的model取不到值的解決方法
今天小編就為大家分享一篇angularJs select綁定的model取不到值的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10ionic3實戰(zhàn)教程之隨機布局瀑布流的實現(xiàn)方法
這篇文章主要給大家介紹了關于ionic3實戰(zhàn)教程之隨機布局瀑布流的實現(xiàn)方法,文中通過示例代碼和圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-12-12