[英]Angular: display content projection with nested children
我有一個組件,我想在子組件中顯示可配置的 html。 客戶端無法訪問子組件。 所以我認為我正在尋找的是內容投影
<Parent>
<ng-template #editTemplate> //custom
<button>Edit Me </button>
</ng-template>
<child1>
...
<child4>
I would like to show the #editTemplate here
</child4>
</child1>
</Parent>
所以在child4
里面
我有這個 HTML
<div>
<ng-content #editTemplate></ng-content>
</div>
但是我無法顯示按鈕。 我在這里做錯了什么?
您在這里擁有的是內容投影和依賴注入的有趣組合。
<ng-template #editTemplate>
被內容投影到Parent
組件中
<Parent>
<ng-template #editTemplate> <--- projected into <Parent>
<button>Edit Me </button>
</ng-template>
</Parent>
所以Parent
可以通過Content Child直接引用它,如果您的Parent
組件看起來像這樣:
@Component({
selector: 'parent',
template: `
<h2>Parent here!</h2>
<ng-content></ng-content> <--- #editTemplate will get projected here
<child1></child1>
`,
styles: [`h1 { font-family: Lato; }`],
})
export class ParentComponent {
@ContentChild('editTemplate') editTemplate: TemplateRef<any>; // <--- reference to #editTemplate
}
然而, child4
嵌套了好幾層,所以依賴注入是你的朋友,否則你需要在每一層配置一個引用來完成從Parent
到child4
的鏈。
但是,使用 DI,您可以將Parent
組件直接注入child4
,然后 child4 可以訪問Parent
組件實例上的editTemplate
引用並使用*ngTemplateOutlet插入來自該TemplateRef
的視圖。
所以child4
可能看起來像這樣:
@Component({
selector: 'child4',
template: `
<h3>Child 4 here!</h3>
<div>And here's the injected template:</div>
<ng-container *ngTemplateOutlet="projectedTemplate"></ng-container> <--- use *ngTemplateOutlet to render editTemplate
`,
styles: [`h1 { font-family: Lato; }`],
})
export class Child4Component {
projectedTemplate: TemplateRef<any>;
constructor(private parentComponent: ParentComponent) {} // <-- inject ParentComponent instance
ngOnInit() {
this.projectedTemplate = this.parentComponent.editTemplate; // <-- set *ngTemplateOutlet to editTemplate
}
}
這是一個 StackBlitz展示了這種方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.