ViewContainerRef 在 ngAfterViewInit 中调用时未定义

编程入门 行业动态 更新时间:2024-10-16 18:32:21
本文介绍了ViewContainerRef 在 ngAfterViewInit 中调用时未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想在初始化父组件时动态创建子组件,但是当我尝试在 ngAgterViewInit() 中创建它时,它抛出 ViewContainerRef 未定义的错误.

component.ts

 @ViewChild('container', {read: ViewContainerRef}) 容器:ViewContainerRef;构造函数(私有解析器:ComponentFactoryResolver){}ngAfterViewInit(){const factory = this.resolver.resolveComponentFactory(ChildComponent);this.container.createComponent(工厂);//此处未定义容器}

component.html

<预><代码>...<div class="row" #container ></div>...

解决方案

由于 divngIf 条件块内,它可能在 中不可用ngAfterViewInit.您可以通过使用 ViewChildrenQueryList.changes 事件监视元素的存在来保护代码免受这种可能性的影响:

@ViewChildren('container', { read: ViewContainerRef }) 容器:QueryList;ngAfterViewInit() {如果(this.containers.length > 0){//容器已经存在this.addComponent();};this.containers.changes.subscribe(() => {//容器已经添加到 DOMthis.addComponent();});}私人添加组件(){const 容器 = this.containers.first;const factory = this.resolver.resolveComponentFactory(ChildComponent);container.createComponent(工厂);}

有关演示,请参阅此 stackblitz.

I want to dynamically create a child component when the parent component is initialised, but when I tried to create it in ngAgterViewInit(), it throws the error that the ViewContainerRef is undefined.

component.ts

  @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {
  }

  ngAfterViewInit(){
    const factory = this.resolver.resolveComponentFactory(ChildComponent);
    this.container.createComponent(factory); //container is undefined here

  }

component.html

...
<div class="row" #container ></div>
...

解决方案

Since the div is inside an ngIf conditional block, it may not be available in ngAfterViewInit. You can protect the code against that possibility by monitoring the presence of the element with ViewChildren and the QueryList.changes event:

@ViewChildren('container', { read: ViewContainerRef }) containers: QueryList<ViewContainerRef>;

ngAfterViewInit() {
  if (this.containers.length > 0) {
    // The container already exists
    this.addComponent();
  };

  this.containers.changes.subscribe(() => {
    // The container has been added to the DOM
    this.addComponent();
  });
}

private addComponent() {
  const container = this.containers.first;
  const factory = this.resolver.resolveComponentFactory(ChildComponent);
  container.createComponent(factory);
}

See this stackblitz for a demo.

这篇关于ViewContainerRef 在 ngAfterViewInit 中调用时未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 17:06:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026959.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未定义   ViewContainerRef   ngAfterViewInit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!