要实现Angular中的动态组件,可以按照以下步骤进行操作:
首先,确保已经安装了Angular CLI并创建了一个新的Angular项目。
在项目的根目录下,通过以下命令创建一个新的组件:
ng generate component dynamic-component
这将在src/app目录下创建一个名为dynamic-component的组件。
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-dynamic-component',
template: `
{{ dynamicData }}
`,
})
export class DynamicComponentComponent {
@Input() dynamicData: string;
}
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { DynamicComponentComponent } from './dynamic-component/dynamic-component.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
loadComponent() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponentComponent);
const componentRef = this.container.createComponent(componentFactory);
componentRef.instance.dynamicData = '这是动态组件的数据';
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { DynamicComponentComponent } from './dynamic-component/dynamic-component.component';
@NgModule({
declarations: [
AppComponent,
DynamicComponentComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
这样,当点击"加载动态组件"按钮时,Angular将会动态创建并加载dynamic-component组件,并将数据传递给该组件显示。