问题描述
我需要从门户动态地附加和分离一组组件的实例,而无需每次附加时都重新初始化它,因为这会大大降低应用程序的性能。
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();
这是this question中解释的方式。但是每次重新附加组件时,它都会重新初始化。
解决方法
我相信您最好使用组件工厂以便在运行时加载组件:
https://angular.io/guide/dynamic-component-loader#dynamic-component-loader