Angular Component Lifecicle not Triggered inside ViewContainerRef.createComponent + OnPush

Viewed 74

When you dynamically create a component using the ViewContainerRef.createComponent method, if the Child Component has changeDetection: ChangeDetectionStrategy.OnPush the Child Component content lifecycle is not triggered.

  private attachChildComponent = (childComponent: ComponentType<any>, container: ViewContainerRef) => {
      const componentFactory = this.factor.resolveComponentFactory(childComponent);
      const childComponentRef = container.createComponent(componentFactory);
  };
1 Answers

When we use changeDetection: ChangeDetectionStrategy.OnPush we need to trigger the change detection manually, using the ComponentRef.changeDetectorRef.detectChanges()

const childComponentRef = this.childContainer.createComponent(componentFactory);
childComponentRef.changeDetectorRef.detectChanges(); // force OnPush to detect

Related