2017-02-23 28 views
2

我很難嘗試將上下文數據傳遞到我動態創建的嵌入視圖。Angular - 使用createEmbeddedView設置上下文

注:我採用了棱角分明2.4.7

這裏是我whant實現:


在我DialogPresetComponent(對話框的預設。 component.html)

此組件的視圖包含對我的對話框架內使用準備好了一堆模板:

<template #presetInfo> 
    {{options.description}} // Note this binding ! Here is the problem 
</template> 

仍然在這個組件,我得到一個裁判這些模板是這樣的:

@ViewChild('presetInfo', { read: TemplateRef }) presetInfo: TemplateRef<any>; 

然後,我存儲這個模板參考在一個DialogService中,所以我可以稍後訪問它們,並從其他地方訪問它們。


DialogComponent(dialog.component.html)

這裏是我的模式的模板:

<div class='c-header'> 
</div> 
<div class='c-body'> 
    <div #container></div> 
</div> 
<div class='c-footer'> 
</div> 

DialogComponent(對話.component.ts)

在我DialogComponent搶在容器上的參考這樣的:

@ViewChild('container', {read: ViewContainerRef }) containerRef: ViewContainerRef; 

我還定義,我想從我的動態地訪問屬性注入模板:

options: DialogOptions = { title: 'Dialog title' }; 

我在做什麼:

我試圖把模板#presetInfo#container的內,並與我DialogComponent的

所以finaly的背景下,我注入我的模板,我的組件賦予它的權利上下文:

在我的DialogComponent(dialog.component。TS)

// Where templateRef is the template previously defined in DialogPresetComponent 
createEmbeddedView(templateRef: TemplateRef<any>) { 
    this.containerRef.createEmbeddedView(templateRef, this);  
} 

的問題來自於一個事實,即結合{{options.description}}在我的注入模板不工作,通過正確的背景下(甚至當「這個」在我的情況)通過createEmbeddedView。

框架告訴我的選擇是不確定的。

我在這裏失蹤了什麼?

沒有關於這個「背景」的東西很多文檔,所以我想我不這樣做的正確的方式....

任何線索或提示,歡迎!

謝謝!

+0

似乎你通過'this'作爲上下文。這是故意的嗎? –

+1

是的,這是故意的,我認爲,通過'這'將使我所有的組件成員都可以在包含的模板中使用。 就像我的模板是組件視圖的一部分... – Clement

回答

5
this.containerRef.createEmbeddedView(templateRef, {$implicit: {description: 'some description'} });  
<template #presetInfo let-options> 
    {{options.description}} // Note this binding ! Here is the problem 
</template> 

如果傳遞的對象與屬性$implicit然後就let-xxx足以使可作爲模板內xxx$implicit值。

對於其他屬性,你需要let-yyy="someProp"使其可作爲yyy在模板中。

+0

該死的工作! 非常感謝,您從哪裏獲得有關此$隱式屬性和您解釋的規則的文檔? 從角度源代碼? – Clement

+0

我在Angular2 GitHub問題或Pull Request中討論過它。不記得確切的,但我一直在緊跟整個2016年的Angular2發展。 –

+0

不錯的一個!由於 – Clement

相關問題