Angular 2 支持动态组件,可以通过使用 ComponentResolver 将组件添加到主模块中。这些动态组件还可以具有自己的路由,允许在应用程序中动态加载和卸载它们。以下是一个简单的示例,演示如何实现具有自己路由的动态组件:
import { Component } from '@angular/core';
@Component({
selector: 'dynamic-comp-example',
template: 'Dynamic Component Example
'
})
export class DynamicCompExampleComponent {
}
import { RouterModule } from '@angular/router';
import { DynamicCompExampleComponent } from './dynamic-comp-example.component';
@NgModule({
imports: [
RouterModule.forChild([
{ path: '', component: DynamicCompExampleComponent }
])
],
exports: [RouterModule]
})
export class DynamicCompRouterModule { }
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { DynamicCompRouterModule } from './dynamic-comp-router.module';
@Component({
selector: 'app-main',
template: ''
})
export class AppComponent {
@ViewChild('dynamicComp', {read: ViewContainerRef}) dynamicCompRef: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {}
ngAfterViewInit() {
// 从 ComponentResolver 中解析动态组件
const dynamicCompFactory = this.resolver.resolveComponentFactory(DynamicCompExampleComponent);
// 在视图容器中创建动态组件
const dynamicCompRef = this.dynamicCompRef.createComponent(dynamicCompFactory);
// 使用自己的路由
dynamicCompRef.instance.router.resetConfig(DynamicCompRouterModule.forChild([{ path: '', component: dynamicCompRef.instance }]));
// 如果需要卸载组件,可以使用以下代码
// dynamicCompRef.destroy();
}
}