要在Angular 7中在现有模块中插入新的动态组件,可以按照以下步骤进行操作:
DynamicComponent
的组件。import { Component } from '@angular/core';
@Component({
selector: 'app-dynamic-component',
template: `
Dynamic Component
`
})
export class DynamicComponent {}
DynamicComponent
。例如,在AppModule
中声明。import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DynamicComponent } from './dynamic.component';
@NgModule({
imports: [BrowserModule],
declarations: [DynamicComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
ViewContainerRef
和ComponentFactoryResolver
来动态创建和插入新的组件。import { Component, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-existing-component',
template: `
Existing Component
`
})
export class ExistingComponent {
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private viewContainerRef: ViewContainerRef
) {}
ngAfterViewInit() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
const componentRef = this.viewContainerRef.createComponent(componentFactory);
// 可以通过 componentRef.instance 访问到新创建的动态组件实例
}
}
在现有组件的模板中,使用ViewContainerRef
的createComponent()
方法来创建动态组件的实例,并将其插入到指定的容器中。可以通过componentRef.instance
来访问新创建的动态组件实例。
请注意,要使用 这样,现有组件就会在渲染时动态地将新的动态组件插入到指定的容器中。ViewContainerRef
和ComponentFactoryResolver
,需要在构造函数中注入它们,并将ViewContainerRef
与一个带有#dynamicComponentContainer
模板引用变量的相关内容