基本使用方法
- 首先在HTML的文件中引入,用来存放动态加载的组件
<ng-template #target></ng-template>
- 简介相关的api
ViewChild:一个属性装饰器,用来从模板视图中获取对应的元素,可以通过模板变量获取,获取时可以通过 read 属性设置查询的条件,就是说可以把此视图转为不同的实例
ViewContainerRef :一个视图容器,可以在此上面创建、插入、删除组件等等
ComponentFactoryResolve:一个服务,动态加载组件的核心,这个服务可以将一个组件实例呈现到另一个组件视图上
- 接下来在component.ts文件中进行一些逻辑处理
引入相关的依赖
import {
Component,
ComponentFactoryResolver,
ComponentRef,
ViewChild,
ViewContainerRef
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { exampleComponent } from '..example.component';
想关的class里对组件的创建
// 这里的target与HTML里的需要对应上
@ViewChild('target', { read: ViewContainerRef })
formContainer: ViewContainerRef;//用来创建等对组件进行相关操作的
public formContainerRef: ComponentRef<any>; // 通过formContainer调用相关api创建出来的组件容器
public isLoading = true;
public hasMask: boolean;
constructor(private route: ActivatedRoute,
private componentFactoryResolver: ComponentFactoryResolver) {
}
接下来进行相关的初始化工作
ngOnInit() {
this.route.params
.subscribe(params => {
this.exampleservice.get(params['id']).subscribe(res => {
this.isLoading = false;
if (res.example.length === 0) {
//满足相关的条件后就在ngtamplate中添加相关的组件
this.createComponent(exampleComponent, res, params);
}
});
});
}
为了代码的可读性,将相关逻辑进行封装
private createComponent(component, res, params) {
this.formContainer.clear();//调用相关api进行清除容器内容
//resolveComponentFactory 解析一个已经声明的组件得到一个可动态加载的 componentFactory
const compFactory = this.componentFactoryResolver.resolveComponentFactory(component);
//createComponent函数将解析出来的componentFactory动态呈现到容器视图上
this.formContainerRef = this.formContainer.createComponent(compFactory);
//这里是向被加载的exampleComponent中Input一个变量initialFormData,formId
this.formContainerRef.instance.initialFormData = res;
this.formContainerRef.instance.formId = params['id'];
//这里是接受从exampleComponen组件中output的值
this.formContainerRef.instance.loadingStatus
.subscribe(data => {
this.hasMask = data;
});
}
- 针对如何从被加载的组件中获取其output的值,因为上边的代码中使用的是subscribe的形式,所以在exampleComponent中也对应这相关代码的定义的执行。
exampleComponent.ts
//由于上边使用的是subscribe的形式
@Output() loadingStatus: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
//相关逻辑的使用
public changeLoadingStatus(xxexampleForm) {
if (xxexampleForm.valid) {
this.exampleStatus = true;
this.loadingStatus.next(this.exampleStatus);
}
小结
其实就把相关的组件数据,在ng-template的ts中进行获取,然后根据相关的数据去加载不同的组件,实际项目中,是用来根据call api获取的的不同数据去加载三个类似的form表单。这三个表单call的是同一个api只不过传入的参数不同。
网友评论