2017-05-05 64 views
1

採用了棱角分明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-templatengTemplateOutlet作爲新模板傳遞。

在這個例子中,my-native-componentmy-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/

我在做什麼錯?

回答

2

想法是,你需要向下傳遞模板層次樹。 見plunker這裏:https://plnkr.co/edit/hwww2QXDh9Je5Bc9ld3O?p=preview

在我的本地成分:

<ng-container *ngTemplateOutlet="template; context: {$implicit: value}"></ng-container> 

在我的組分:

<my-native-component *ngIf="!useCustom" [value]="value" [template]="template"> 
    <ng-template [ngTemplateOutlet]="templateVariable"></ng-template> 
</my-native-component> 

在我的應用程序內:

<my-component [value]="value" [useCustom]="false" [template]="test"><!-- toggle useCustom true/false --> 
    <ng-template #test let-value> 
    <p><strong>Value rendered in user supplied template: {{value}}</strong></p> 
    </ng-template> 
</my-component> 

將這個在組件中允許傳輸模板。

@Input() 
private template: TemplateRef; 

必須牢記這一點。 <ng-template>必須需要一個容器來輸出它的內容。它默認隱藏在HTML中。 https://angular.io/docs/ts/latest/guide/structural-directives.html#!#template

+0

謝謝,但這是在'my-native-component'中定義了一個新模板。你知道如何讓'my-native-component'渲染傳遞給'my-component'的模板嗎? – Josh

+0

看到我更新的代碼和plunker。 – wannadream

+0

啊,我沒有想過通過參考作爲輸入。謝謝! – Josh

0

當您添加ngTemplateOutlet時,它不會成爲模板,因此組件將不會將其視爲@ContentChild(TemplateRef)。

<ng-template [ngTemplateOutlet]="templateVariable"></ng-template> 
相關問題