您可以使用componentFactoryResolver 和viewContainerRef 动态地渲染组件。
这是一个简单的例子,我创建了一个名为 Cmp1Component 的组件,它将被动态渲染。
App.module.ts
@NgModule({
declarations: [
AppComponent,
Cmp1Component,
Cmp2Component
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent],
entryComponents:[
Cmp1Component
]
})
export class AppModule { }
App.component.html
A component will be rendered down here:
<div #placeholder></div>
App.component.ts
import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { Cmp1Component } from './cmp1/cmp1.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public done = false;
@ViewChild("placeholder", {read: ViewContainerRef}) placeholderRef: ViewContainerRef;
constructor(
public viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) {
}
ngAfterViewChecked(): void {
if(!!this.placeholderRef && !this.done){
this.done = true;
const factory = this.componentFactoryResolver.resolveComponentFactory(Cmp1Component);
const componentRef = this.placeholderRef.createComponent(factory);
componentRef.changeDetectorRef.detectChanges();
}
}
}
结果:
一件事:您可能不需要将逻辑放入ngAfterViewChecked 循环中。我做了这个逻辑只是为了向你展示它是如何工作的。如果你真的把代码放在一个函数中,当所有东西都被渲染时就会执行,那么你肯定知道placeHolderRef不是空的或未定义的。