【问题标题】:Pass context to template in dynamically created component在动态创建的组件中将上下文传递给模板
【发布时间】:2019-07-14 08:09:31
【问题描述】:

我想创建一个类似于工具提示控件的组件。问题是它只适用于简单的文本,但是当我想传递一个更复杂的 ng-template(如绑定等)时,它会中断。一般来说,我创建了一个主机组件,其中将显示传递的模板和一个创建组件的指令。 但似乎传递的上下文对于传递的模板不可见。

指令:

@HostListener("mouseenter")
enter() {
    const factory = this.resolver.resolveComponentFactory(CustomContainerComponent);
    const injector = Injector.create([]);

    this.vcr.createComponent<CustomContainerComponent>(factory, 0, injector, this.generate());
}

generate(): any[][] {
    const context = { // this is mocked for now
      name:"John"
    };
    const viewRef = this.customControl.createEmbeddedView(context);

    return [viewRef.rootNodes];
}

这里是 stackblitz 的一个简单例子: https://stackblitz.com/edit/angular-mzhccs

【问题讨论】:

  • 在 app.component.html 上试试这个...值正在更新 - 但仅在第一个按钮上 &lt;div style="display:flex; flex-direction:column;"&gt; &lt;button [customControl]="ctrl2"&gt;Working&lt;/button&gt; &lt;button [customControl]="ctrl1"&gt;Not working&lt;/button&gt; &lt;/div&gt; &lt;ng-template #ctrl2&gt; Working &lt;/ng-template&gt; &lt;ng-template #ctrl1 let-name="name"&gt; not-working: {{name}} &lt;/ng-template&gt;
  • 仍然无法与上下文绑定(名称未显示)。我已经设法让它工作,在指令中我将this.customControl.createEmbeddedView(context); 更改为this.vcr.createEmbeddedView(this.customControl, context);,现在它似乎工作了。

标签: angular angular2-template angular2-directives


【解决方案1】:

viewRef detechange 可以解决问题:

const viewRef = content.templateRef.createEmbeddedView(context);
viewRef.detectChanges();

然后上下文将被正确填充并按预期绑定到模板。

【讨论】:

    猜你喜欢
    • 2017-12-10
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多