在ng模板内部访问时,ViewContainerRef未定义

问题描述

我正在尝试在unsubscribedisclaimer内部动态加载组件。

下面是我的HTML

<ng-template #TooltipInfo>
    <p #unsubscribedisclaimer></p>
</ng-template>

在Component.ts

  @ViewChild('unsubscribedisclaimer',{ read: ViewContainerRef,static: true }) unsubscribedisclaimer: ViewContainerRef;

  this.createComponent(unsubscribedisclaimer,this.unsubscribedisclaimer);


  createComponent (content,view: ViewContainerRef) {
    console.log(view);
    const componentType = this.contentMappings[content.type];

    if(view) {
      this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
      this.componentReference = view.createComponent(this.componentFactory);
      this.componentReference.instance.contentOnCreate(content);
    }
    
  }

但是由于未知原因,视图为undefined

在这里做错了什么?

解决方法

您可以采用这种方法:不要创建指令,而是给ng-template提供一个ID

<ng-template #dynamicComponent></ng-template>

在组件类中使用@ViewChild装饰器

@ViewChild('dynamicComponent',{ read: ViewContainerRef }) myRef

ngAfterViewInit() {
    const factory = this.componentFactoryResolver.resolveComponentFactory(component);
    const ref = this.myRef.createComponent(factory);
    ref.changeDetectorRef.detectChanges();
}

希望您可以在您的方法中应用它。

,

static的值更改为false是可行的。

@ViewChild('unsubscribeDisclaimer',{ read: ViewContainerRef,static: false }) unsubscribeDisclaimer: ViewContainerRef;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...