简体   繁体   中英

Destroy component instance once created from service

I'm creating components dynamic using a service. Component was created, but the ngOnDestroy lifecycle look is not getting called.

Below is my service file code.

@Injectable()
export class CreateComponentService implements OnDestroy {
  private rootViewContainer: ViewContainerRef;
  private componentFactory: ComponentFactory<any>;
  private componentReference;
  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

  setRootViewContainerRef(view: ViewContainerRef): void {
    this.rootViewContainer = view;
  }

  createComponent(content, type) {
    this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
    this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);
    this.componentReference.instance.contentOnCreate(content);
  }

  ngOnDestroy() {
    // Destroy components to avoide memory leaks
    this.componentReference.destroy();
  }
}

In Component.ts

constructor(private service: CreateComponentService) {}

      data.forEach(response => {
        this.service.createComponent(response, type);
      });

Please show me the best way to destroy the component instance

You don't explicitly destroy the service, and the service onDestroy method won't be called.

You can try to detach the views from the change-detection tree, which is similar to what you need,

private insertComponent(componentType): void {
    const factory = this.factoryResolver.resolveComponentFactory(componentType);
    var containerRef = this.rootViewContainer.createComponent(factory);
    // always get the most recently appended node
    var viewRef = this.rootViewContainer.get(this.rootViewContainer.length - 1);
    viewRef.detach();
    containerRef = null;
}

containerRef will be garbage collected eventually. And since you detach the view, it will behave like static content. Note that if you destroy containerRef , the associated view/html will also get destroyed.

update: demo https://stackblitz.com/edit/dynamic-component-example-swrj8j?file=src/app/service-based/factory.service.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM