首页 文章

在ngIf中动态创建组件

提问于
浏览
1

我正在使用Angular 6,我已经尝试按照答案here但我无法让它工作

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

1 回答

  • 2

    要摆脱 ExpressionChangedAfterItHasBeenCheckedError ,您可以使用this Angular In Depth blog post中建议的技术之一:

    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
      });
    }
    

    Create the component asynchronously with setTimeout

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

相关问题