连接到门户时仅初始化组件一次

Sac*_*han 6 angular angular-cdk

我需要从门户动态附加和分离一组组件的实例,而无需每次附加时都重新初始化它,因为这会大大降低应用程序的性能。

portal = new ComponentPortal(MyComponent);
this.portalHost = new DomPortalHost(
      this.elementRef.nativeElement,
      this.componentFactoryResolver,
      this.appRef,
      this.injector
    );

const componentRef = this.portalHost.attach(this.portal);
componentRef.instance.myInput = data;
componentRef.instance.myOutput.subscribe(...);
componentRef.changeDetectorRef.detectChanges();
Run Code Online (Sandbox Code Playgroud)

这就是这个问题中解释的方式。但每次重新连接组件时,它都会重新初始化。

Mar*_*nto 0

我相信您最好使用组件工厂来在运行时加载组件:

https://angular.io/guide/dynamic-component-loader#dynamic-component-loader