如标题所述,是否有一种方法可以在Angular中以编程方式呈现(到DOM元素)一个组件?
例如,在React中,我可以使用ReactDOM.render
将组件转换为DOM元素。 我想知道在Angular中是否也有类似的功能?
如标题所述,是否有一种方法可以在Angular中以编程方式呈现(到DOM元素)一个组件?
例如,在React中,我可以使用ReactDOM.render
将组件转换为DOM元素。 我想知道在Angular中是否也有类似的功能?
首先,在您希望放置动态加载组件的位置,您需要在HTML文件中拥有一个模板。
<ng-template #placeholder></ng-template>
在组件中,您可以在构造函数中注入DynamicFactoryResolver
。一旦执行 loadComponent()
函数,DynamicComponent
就会在模板中可见。 DynamicComponent
可以是您想要显示的任何组件。
import { Component, VERSION, ComponentFactoryResolver, ViewChild, ElementRef, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('placeholder', {read: ViewContainerRef})
private viewRef: ViewContainerRef;
constructor(private cfr: ComponentFactoryResolver) {}
loadComponent() {
this.viewRef.clear();
const componentFactory = this.cfr.resolveComponentFactory(DynamicComponent);
const componentRef = this.viewRef.createComponent(componentFactory);
}
}
这里有一个Stackblitz。
loadComponent
函数的作用是:
resolveComponentFactory
);createComponent
);componentRef
来修改该组件实例的公共属性或触发公共函数等操作。ComponentFactoryResolver
不再需要。因此,简化版本为:import { Component, VERSION, ViewChild, ElementRef, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('placeholder', {read: ViewContainerRef})
private viewRef: ViewContainerRef;
loadComponent() {
this.viewRef.clear();
const componentRef = this.viewRef.createComponent(DynamicComponent);
}
}