附加到门户时仅初始化一次组件

问题描述

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...