本文介绍了在ngIf内部动态创建组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 6,并且尝试按照答案此处但我无法正常工作

I am using Angular 6 and I've tried following the answer here but I can't get it to work

export class AppComponent implements AfterContentInit, AfterViewInit {
  defaultToTrue = true;
  @ViewChildren('parent', { read: ViewContainerRef }) parent: QueryList<ViewContainerRef>;

  constructor(private cfr: ComponentFactoryResolver) { }

  ngAfterViewInit(){
    const resolve = this.cfr.resolveComponentFactory(ChildComponent);
    this.parent.changes.subscribe(changes => {
      this.parent.createComponent(resolve); //Error
    });
  }

}

HTML:

<div *ngIf="defaultToTrue">
  <div #parent></div>
</div>

StackBlitz

推荐答案

要摆脱ExpressionChangedAfterItHasBeenCheckedError,您可以使用此Angular In Depth博客文章:

使用ChangeDetectorRef.detectChanges 进行强制更改检测:

Force change detection with ChangeDetectorRef.detectChanges:

constructor(private cfr: ComponentFactoryResolver, private cd: ChangeDetectorRef) { }

ngAfterViewInit(){
  const resolve = this.cfr.resolveComponentFactory(ChildComponent);
  this.parent.changes.subscribe(changes => {
    this.parent.createComponent(resolve);
    this.cd.detectChanges();  // Trigger change detection
  });
}

setTimeout 异步创建组件:

Create the component asynchronously with setTimeout:

ngAfterViewInit(){
  const resolve = this.cfr.resolveComponentFactory(ChildComponent);
  this.parent.changes.subscribe(changes => {
    setTimeout(() => { this.parent.createComponent(resolve); });
  });
}

这篇关于在ngIf内部动态创建组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 09:24