【问题标题】:How to insert dynamically created component into the template如何将动态创建的组件插入到模板中
【发布时间】:2021-02-15 22:40:57
【问题描述】:

我有使用 ComponentFactoryResolver 动态创建的组件。我想把它插入到模板中。我尝试使用 templateRef 或 viewContainerRef 但没有一个成功。

ComponentOutlet 需要组件类而不是实例,ViewContainerRef 需要模板引用。它们都不适用于创建的实例。

如何使它与创建的组件实例一起工作?有什么办法吗?

解决方案

我使用 ViewContainerRef 的 insert 方法解决了我的问题

【问题讨论】:

  • 你能展示一下你的尝试吗?
  • ViewContainerRef 有一个 createComponent 方法。

标签: angular


【解决方案1】:

你需要一个视图容器的引用:

export class ExampleComponent implements AfterViewInit {
@ViewChild('contentElement', { read: ViewContainerRef }) contentElement: ViewContainerRef;
    
    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private ref: ChangeDetectorRef
    ) {}
    
    ngAfterViewInit() {
            const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
                yourComponent
            );

            const contentElement = this.contentElement;
            contentElement.clear();
            const component = contentElement.createComponent(componentFactory);
            this.ref.detectChanges();
        }
    }
<ng-template #contentElement></ng-template>

【讨论】:

  • 我已经使用 ComponentFactoryResolver 动态创建了组件,正如我在上面所说的,我已经实例化了组件。 createComponent 方法 ViewContainerRef 需要一个 ComponentType 类而不是实例。
猜你喜欢
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 2020-09-16
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多