以模态框举例,经常有这种需求:当需要模态框时,建立模态框,而使用完成后,希望将其销毁,以期该模态框不再继续消耗资源,同时再次打开时可以是一个全新的模态框(重新初始化)。
    那么,实现这样的动态加载组件有几个问题需要考虑。

    1. 创建和初始化;
    2. 组件传值 @Input @Output;
    3. 组件的销毁。

    以一个简单模态框动态创建举例进行说明:

    1. // 建立容器
    2. @ViewChild('siteGroupEditModal', { read: ViewContainerRef }) siteGroupEditModalContainer: ViewContainerRef;
    3. constructor(
    4. private resolver: ComponentFactoryResolver,
    5. ) { }
    6. // 动态创建
    7. // WorkspacePagesIndexSiteGroupCreateEditModalComponent是已经建立好的要加载的组件
    8. // 清理容器
    9. this.siteGroupEditModalContainer.clear();
    10. const factory: ComponentFactory<WorkspacePagesIndexSiteGroupCreateEditModalComponent> =
    11. this.resolver.resolveComponentFactory(WorkspacePagesIndexSiteGroupCreateEditModalComponent);
    12. const componentRef = this.siteGroupEditModalContainer.createComponent(factory);
    13. // @Input 输入值传递
    14. componentRef.instance.groupName = '';
    15. componentRef.instance.groupColor = '#FFF';
    16. componentRef.instance.createGroup = 'create';
    17. componentRef.instance.selectNodeId = 'root';
    18. // @Output 输出值传递
    19. componentRef.instance.modalClosed.subscribe(() => {
    20. // 组件通过内部的destroySubjuect实现自动销毁
    21. componentRef.destroy();
    22. });
    1. <-- 动态创建Html标签 -->
    2. <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();
      }
    }