【问题标题】:ViewContainerRef is undefined while accessing inside ng templateViewContainerRef 在访问 ng 模板时未定义
【发布时间】:2021-02-18 08:19:16
【问题描述】:

我正在尝试在内部动态加载组件,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);
    }
    
  }

但不知什么原因,view是undefined

我在这里做错了什么?

【问题讨论】:

  • 您在组件生命周期的哪个时间点调用this.createComponent?只有在ngAfterViewInit 之后才能访问模板视图。所以如果这个方法在这个钩子之前被调用,它将是未定义的。试着把你的电话移到这个钩子里。
  • 我厌倦了 ngOnInit 和 ngAfterViewInit,即使设置了超时

标签: angular typescript angular-dynamic-components


【解决方案1】:

static 值更改为false 有效。

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

【讨论】:

  • 根据角度文档True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.,这意味着true 使组件在ngOnInit 中可用,false 使其在ngAfterViewInit 中可用。当您将其更改为 false 时,您是从 ngAfterViewInit 调用它吗?
  • @Edward 是的,你是对的,我在 ngOnInit 方法上使用 setTimeout,所以它工作正常,现在我将它移到 ngAfterviewInit
【解决方案2】:

您可以采取这种方法:不要创建指令,而是给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();
}

希望你能在你的方法中应用这一点。

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 2021-11-15
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多