angular 动态组件使用
2019-08-20 本文已影响0人
咕嘟咕嘟li
- 新建动态Loading组件
- 在app.module.ts中(或者其它module中)注册该组件,如下:
import { LoadingComponent } from 'path';
@NgModule({
declarations: [
...
LoadingComponent
],
imports: [
...
],
entryComponents: [ LoadingComponent ], // 动态添加组件
...
})
3.Test组件的组件中还要再引入Loading组件,然后使用ComponentFactoryResolver
来动态添加Loading组件
import { Component, OnInit, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { LoadingComponent } from 'path';
@Component({
...此处省略不写
})
export class TestComponent implements OnInit {
constructor(
public componentFactoryResolver: ComponentFactoryResolver,
public viewContainerRef: ViewContainerRef
) { }
ngOnInit() {
this.loadComponent('loading');
setTimeout(() => {
// 6秒后移除动态添加的组件
this.viewContainerRef.clear();
}, 6000);
}
// 动态添加组件到页面
loadComponent(data) {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(LoadingComponent);
this.viewContainerRef.clear();
const componentRef = this.viewContainerRef.createComponent(componentFactory);
// 如果要给组件传参可在组件内定义好,然后用以下方式传递参数
// (componentRef.instance).data = data;
}
}