Angular2 Dynamic content loading throws Expression changed exception

后端 未结 1 1639
终归单人心
终归单人心 2021-02-13 02:22

I\'m creating a generic Gantt visualization component.

The part where I will display the weeks and tasks is generic, but every row will have a header that I want to be d

1条回答
  •  执笔经年
    2021-02-13 02:46

    The error says it all:

    It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook?

    You've created component dynamically ("outside" of angular lifecycle), this means you need to control change detection manually.

    So that is what you need to do:

    1) After creating a component fire detectChanges() for it

    2) Before disposing detach() change detection;

    Here is example of my directive that creates component dynamically:

    export class ValidationMessageDirective implements AfterViewInit, OnDestroy {
    
      private validationMessageComponent: ComponentRef = null;
    
      ngAfterViewInit(): void {
        let factory = this.componentFactoryResolver.resolveComponentFactory(this.vmComp);
        this.ngOnDestroy();
        this.validationMessageComponent = this.viewContainer.createComponent(factory, null, this.viewContainer.injector);
        this.validationMessageComponent.changeDetectorRef.detectChanges();
      }
    
      ngOnDestroy(): void {
        if (this.validationMessageComponent) {
          this.validationMessageComponent.changeDetectorRef.detach();
          //this.validationMessageComponent.destroy();
        }
      }
    
      constructor(
        private viewContainer: ViewContainerRef,
        private componentFactoryResolver: ComponentFactoryResolver,
        @Inject(ValidationMessageComponent) private vmComp: Type
      ) { }
    }
    

    Related issue: https://github.com/angular/angular/issues/11007

    0 讨论(0)
提交回复
热议问题