[英]Angular component with template outlet
我有一個問題組件,該組件有多個實現,但包含一個通用的標題組件。
我的願望是創建一個組件,以便給定問題模型,模板將輸出正確的問題類型。
我已經看到了ngTemplateOutlet
的想法,但是關於它如何工作的文檔很難理解(也許不適合您,但對我來說),並且我無法通過查看示例來確定如何實現此目的。 我認為我不必在哪里重新發明輪子,這似乎是常見的要求。
我之前的嘗試包括一個[ngSwitch]
容器,其中包含許多不同的*ngSwitchCase
,但是如果我可以在外部定義模板並讓questionComponent知道從questionType
到可用的ng-template
的映射,那將是理想的選擇。
例如
export class question {
constructor(public title: string, public questionType: string, public answer: any) {}
}
@Component({
selector: 'app-question',
template: `
<div class="question">
<p>{{q.title}}</p>
<ng-container [ngTemplateOutlet]="theRightTemplate">
</ng-container>
</div>
`})
export class QuestionComponent {
@Input()
question: Question;
}
我目前正在使用Angular 7
有人可以幫我弄清楚如何實現嗎?
好的,我給你舉個例子,並解釋一下:
鏈接: https : //github.com/100cm/at-ui-angular/blob/master/src/app/components/switch/switch.component.ts
對於您的代碼,我們必須定義一個@Input
變量
export class question {
constructor(public title: string, public questionType: string, public answer: any) {}
}
@Component({
selector: 'app-question',
template: `
<div class="question">
<p>{{q.title}}</p>
<ng-container [ngTemplateOutlet]="theRightTemplate">
</ng-container>
</div>
`})
export class QuestionComponent {
@Input()
question: Question;
@Input()
myTemplate:TemplateRef
}
然后將<ng-container>
更改為<ng-template>
(我認為<ng-container>
不能用於模板出口
<ng-template [ngTemplateOutlet]="myTemplate">
好的,然后立即使用您的<app-question>
!
what_ever_html:
<app-question [myTemplate]="my_template"></app-question>
<ng-template #my_template> i am worked now !</ng-template>
希望這對你有幫助!
使用模板制作動態組件有兩件重要的事情。
Template
-第一個是模板本身,需要注入,這里要注意的重要一點是,它需要帶有附加信息的context
,在您情況下, question
詳細信息。 ngTemplateOutlet
需要在其中注入模板的位置。 它接受template
和template
context
。 這是簡單的例子-
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<ng-container *ngTemplateOutlet="templateRef; context: {entry: entry}"></ng-container>
<ng-template #templateRef let-entry="entry">My entry is {{entry | json}}</ng-template>
`,
})
export class AppComponent {
entry = {
label: 'This is a label',
description: 'Desc',
}
}
示例1- https://stackblitz.com/edit/ng-template-outlet-6pzddz
示例2- https://stackblitz.com/edit/angular-reusable-components-ngtemplateoutlet-5nidmd
您可以使用@ContentChild('tableHeader') header: TemplateRef<any>;
在QuestionComponent
您可以使用ContentChild從內容DOM中獲取與選擇器匹配的第一個元素或指令。
如果內容DOM更改,並且有一個新的子項與選擇器匹配,則該屬性將被更新。
您的子component.html
讀為
<ng-template [ngTemplateOutlet]="header"></ng-template> <ng-template [ngTemplateOutlet]="body"></ng-template>
[ngTemplateOutlet]
將讀取屬性值並將內容粘貼到指定模板中的位置
最后,當您從父組件中引用內容時,它將與上述模板一起放置
將內容從父母傳遞給孩子的方法
<app-question> <ng-template #tableHeader></ng-template> <ng-template #body></ng-template> </app-question>
此<ng-template>
所有內容都將放置在子component
在子組件中,您可以添加盡可能多的模板,在這些模板中,所有模板都將與父組件傳遞的內容一起放置-這是將內容從父組件傳遞給子組件的另一種方式-希望這會有所幫助-謝謝您!
點擊這里參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.