採用了棱角分明4.0.3傳遞一個模板內容,這又傳遞到另一個組件
我創建一個組件my-component
,其中有value
輸入,並傳遞了一個ng-template
的內容。例如用法是:
<my-component [value]="value">
<ng-template let-value>
<p><strong>Value rendered in user supplied template: {{value}}</strong></p>
</ng-template>
</my-component>
它的my-component
工作要弄清楚用戶是否在移動設備上或不。如果是這樣,我們想呈現一個my-native-component
。否則,它將呈現my-custom-component
。
我對my-component
到目前爲止的代碼是:
@Component({
selector: 'my-component',
template: `
<my-custom-component *ngIf="useCustom" [value]="value">
<ng-template [ngTemplateOutlet]="templateVariable"></ng-template>
</my-custom-component>
<my-native-component *ngIf="!useCustom" [value]="value">
<ng-template [ngTemplateOutlet]="templateVariable"></ng-template>
</my-native-component>
`
})
class MyComponent {
@ContentChild(TemplateRef)
private templateVariable: TemplateRef;
@Input()
private value: string;
@Input()
private useCustom: bool = false;
}
爲了保持例子簡單,沒有任何的用戶是否是在移動還是不在這裏檢查。相反,useCustom
輸入已添加。
作爲內容被引用爲templateVariable
而傳遞的模板,並通過ng-template
和ngTemplateOutlet
作爲新模板傳遞。
在這個例子中,my-native-component
和my-custom-component
是相同的,除了它們的名字。他們有value
輸入作爲my-component
一樣,也收到一個模板作爲它們的內容。這是my-native-component
樣子:
@Component({
selector: 'my-native-component',
template: `
<h3>my-native-component (value: {{value}})</h3>
<p>Rendered template:</p>
<ng-template [ngTemplateOutlet]="templateVariable" [ngOutletContext]="{$implicit: value}"></ng-template>
<p>Done</p>
`
})
class MyNativeComponent {
@ContentChild(TemplateRef)
private templateVariable: TemplateRef;
@Input()
private value: string;
}
當應用程序被運行,雖然,傳遞模板從來沒有顯示,我想不通爲什麼。也許我錯誤地理解了ng-template
?
完整的可運行的代碼可以在Plunker - https://embed.plnkr.co/fiDECy5gamOLvjPo2uhN/
我在做什麼錯?
謝謝,但這是在'my-native-component'中定義了一個新模板。你知道如何讓'my-native-component'渲染傳遞給'my-component'的模板嗎? – Josh
看到我更新的代碼和plunker。 – wannadream
啊,我沒有想過通過參考作爲輸入。謝謝! – Josh