【问题标题】:Angular 7 inject a dynamic component into the templateAngular 7 将动态组件注入到模板中
【发布时间】:2019-10-30 06:30:34
【问题描述】:

我有以下代码。当 ngOnInit() 运行时,this.widget 包含正确的组件和 this。 data 包含适当的数据。

我无法弄清楚我们如何将动态组件平滑地插入到模板中,以便结果将等同于 ,其中 DynamicComponentthis.widget 中引用的组件。

我尝试了一些在线示例,但无法使它们起作用。有人可以帮忙吗?

import { Component, OnInit, Input } from '@angular/core';
import { IdashService } from '../services/idash.service';

@Component({
  selector: 'app-idash-widget',
  template: `
    <div class="card-body">
      <h5 *ngIf="widgetConfig.title" class="card-title">{{widgetConfig.title}}</h5>

      <!-- I want the component here with the [data] attribute set to this.data -->

    </div>            
  `
})

export class IdashWidgetComponent implements OnInit {

  @Input() widgetConfig;
  widget;
  data;

  constructor(private idashService: IdashService) {
    this.data = {
      someKey: 'someValue'
    }
  }

  ngOnInit() {
    this.widget = this.idashService.moduleConfig.widgets[this.widgetConfig.type];
    console.warn(this.widget, this.data)
  }

}

【问题讨论】:

    标签: javascript node.js angular typescript ecmascript-6


    【解决方案1】:

    试试下面的代码看看它是否有效

    <template #dynamicContainer></template>
    

    在你的组件中

    @ViewChild("dynamicContainer", { read: ViewContainerRef }) container: ViewContainerRef;
    componentRef: ComponentRef<DynamicComponent>;
    constructor(private resolver: ComponentFactoryResolver) {}
    
    createComponent(type) {
        //Clear the container.
        this.container.clear();
        //Create a factory for component.
        const factory = this.resolver.resolveComponentFactory(DynamicComponent);
        //Create a component using the factory
        this.componentRef = this.container.createComponent(factory);
        //Pass the value for @Input properties using a component reference instance method.
        this.componentRef.instance.data = this.data;
    }
    

    在你的模块中确保将你的组件添加到你的 entryComponents 数组中

    entryComponents: [GaugeComponent]
    

    【讨论】:

    • 首先,非常感谢,非常感谢您的帮助。第二:我收到以下错误消息:错误:未找到 GaugeComponent 的组件工厂。你把它添加到@NgModule.entryComponents 了吗?在 noComponentFactoryError ... 我假设组件需要一些特殊处理,但这意味着什么?
    • 再次检查我的答案。忘记添加到模块中
    • 虽然@tony-ngo 的回答是 100% 正确的,但我遇到过一些情况(我现在不记得了)促使我使用@angular/cdk/portal。这个库中有一些额外的检查可以减少你搞砸这些东西的机会。查看文档:material.angular.io/cdk/portal/overview
    • @TonyNgo - 恐怕不会。仍然出现错误:未找到 GaugeComponent 的组件工厂。将组件添加到 entryComponents 下的 ModuleWithProviders 仍然会导致此错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    相关资源
    最近更新 更多