Angular如何在组件中动态加载组件
参考博客1 参考博客2 参考博客3
找到宿主页面
- 在Angular中,我们通常需要一个宿主(Host)来给动态加载的组件提供一个容器。这个宿主在Angular中就是
<ng-template>
### 创建为组件提供容器的指令
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[dl-host]'
})
export class DlHostDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
- 这里注入了一个ViewContainerRef的服务,它的作用就是为组件提供容器,并且提供了一系列的管理这些组件的方法。
- 可以在宿主ts模块文件中通过@ViewChild获取到dl-host的实例,因此进而获取到其中的ViewContainerRef
@ViewChild(DlHostDirective) dlHost: DlHostDirective;
宿主文件的ts文件中
- 引入指令
- 引入需要动态创建的组件
- 创建组件的工厂,引入ComponentFactoryResolver服务
- 具体代码如下
import { Component, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { DlHostDirective } from './dl-host.directive';
import { AComponent } from './a/a.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
@ViewChild(DlHostDirective) dlHost: DlHostDirective;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngAfterViewInit() {
this.dlHost.viewContainerRef.createComponent(
this.componentFactoryResolver.resolveComponentFactory(AComponent)
);
}
}
在.module.ts中将需要生成的组件注册为一个@NgModule.entryComponent
@NgModule({
entryComponents: [AComponent]
})
- entryComponents是所有通过类型进行命令式加载的组件都是入口