Angular - 使用createEmbeddedView设置上下文

Cle*_*ent 4 javascript templates angular

我正在努力将上下文数据传递给动态创建的嵌入视图.

注意:我正在使用Angular 2.4.7

这是我想要实现的目标:


在我的DialogPresetComponent (dialog-preset.component.html)中:

该组件的视图包含一堆模板,可以在我的对话框架中使用:

<template #presetInfo>
   {{options.description}} // Note this binding ! Here is the problem
</template>
Run Code Online (Sandbox Code Playgroud)

仍然在这个组件中,我得到了这样的模板:

@ViewChild('presetInfo', { read: TemplateRef }) presetInfo: TemplateRef<any>;
Run Code Online (Sandbox Code Playgroud)

然后,我将此templateRef存储在DialogService中,以便稍后我可以从其他地方访问它们.


DialogComponent (dialog.component.html)中:

这是我模态的模板:

<div class='c-header'>
</div>
<div class='c-body'>
    <div #container></div>
</div>
<div class='c-footer'>
</div>
Run Code Online (Sandbox Code Playgroud)

DialogComponent (dialog.component.ts)中:

在我的DialogComponent中获取对容器的引用,如下所示:

@ViewChild('container', {read: ViewContainerRef }) containerRef: ViewContainerRef;
Run Code Online (Sandbox Code Playgroud)

我还定义了我想从动态注入的模板访问的属性:

options: DialogOptions = { title: 'Dialog title' };
Run Code Online (Sandbox Code Playgroud)

我想做什么:

我试图把模板#presetInfo的内#container的和我的背景下DialogComponent

最后,我在我的组件中注入我的模板,为其提供正确的上下文:

在我的DialogComponent (dialog.component.ts)中:

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

问题来自于我注入的模板中的绑定{{options.description}}无法正常工作,即使通过createEmbeddedView传递正确的上下文(在我的情况下为'this')也是如此.

框架告诉我选项未定义.

我在这里失踪了什么?

关于这个'上下文'的东西没有很多文档,所以我想我没有以正确的方式做到这一点......

欢迎提供任何线索或提示!

谢谢 !

Gün*_*uer 17

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

如果传递带有属性的对象,$implicit那么就let-xxx足以使$implicitxxx在模板中可用.

对于其他属性,您需要let-yyy="someProp"使其在模板中可用yyy.

  • 那很简短:) (2认同)
  • 我写了'let-options ="options"`并将`this`作为上下文传递 (2认同)