以模态框举例,经常有这种需求:当需要模态框时,建立模态框,而使用完成后,希望将其销毁,以期该模态框不再继续消耗资源,同时再次打开时可以是一个全新的模态框(重新初始化)。
那么,实现这样的动态加载组件有几个问题需要考虑。
- 创建和初始化;
- 组件传值 @Input @Output;
- 组件的销毁。
以一个简单模态框动态创建举例进行说明:
// 建立容器
@ViewChild('siteGroupEditModal', { read: ViewContainerRef }) siteGroupEditModalContainer: ViewContainerRef;
constructor(
private resolver: ComponentFactoryResolver,
) { }
// 动态创建
// WorkspacePagesIndexSiteGroupCreateEditModalComponent是已经建立好的要加载的组件
// 清理容器
this.siteGroupEditModalContainer.clear();
const factory: ComponentFactory<WorkspacePagesIndexSiteGroupCreateEditModalComponent> =
this.resolver.resolveComponentFactory(WorkspacePagesIndexSiteGroupCreateEditModalComponent);
const componentRef = this.siteGroupEditModalContainer.createComponent(factory);
// @Input 输入值传递
componentRef.instance.groupName = '';
componentRef.instance.groupColor = '#FFF';
componentRef.instance.createGroup = 'create';
componentRef.instance.selectNodeId = 'root';
// @Output 输出值传递
componentRef.instance.modalClosed.subscribe(() => {
// 组件通过内部的destroySubjuect实现自动销毁
componentRef.destroy();
});
<-- 动态创建Html标签 -->
<ng-template #siteGroupEditModal></ng-template>
<-- 原始创建Html标签 -->
<app-workspace-pages-index-site-group-create-edit-modal #fromBankSiteDetailGroupCreateModal
[groupName]="groupName" [groupColor]="groupColor" [createGroup]="'edit'"
[selectNodeId]="bankSite?.id">
</app-workspace-pages-index-site-group-create-edit-modal>
// 动态加载的组件
export class WorkspacePagesIndexSiteGroupCreateEditModalComponent
implements OnInit, OnDestroy {
componetDestroyed: Subject<any> = new Subject();
@Input()
groupName: string;
@Input()
groupColor: string;
@Input()
createGroup: 'create' | 'edit';
@Input()
selectNodeId: string;
@Output()
modalClosed = new EventEmitter<never>();
ngOnDestroy() {
this.componetDestroyed.next();
this.componetDestroyed.unsubscribe();
}
closeGroupCreate() {
this.modalClosed.emit();
}
}