Angular从服务中动态创建和销毁组件

时间:2018-06-18 13:40:08

标签: angular

您好我正在动态创建模态弹出

import { 
    Injectable,
    ComponentFactoryResolver,
    EmbeddedViewRef,
    ApplicationRef,
    Injector
} from '@angular/core';


import { ModalWrapComponent } from './../components/modal-wrap/modal-wrap.component';

import { ModalBoxFlatComponent } from './../components/modal-box-flat/modal-box-flat.component';

import { AddHistoryComponent } from './../modals/add-history/add-history.component';


@Injectable()
export class DomService {

    contentCompt: any;
    windowCompt: any;

    constructor(
        private cfr: ComponentFactoryResolver,
        private appRef: ApplicationRef,
        private injector: Injector  
    ) {}

    showModal(objective: String) {
        const contentCmpFactory = this.cfr.resolveComponentFactory(ModalBoxFlatComponent);
        const windowCmpFactory = this.cfr.resolveComponentFactory(ModalWrapComponent);

        if(objective == 'addHistory'){
            const modalCompt = this.cfr.resolveComponentFactory(AddHistoryComponent).create(this.injector);
            this.contentCompt = contentCmpFactory.create(this.injector, [[modalCompt.location.nativeElement]]);
        }

        this.windowCompt = windowCmpFactory.create(this.injector, [[this.contentCompt.location.nativeElement]]);

        document.querySelector('body').appendChild(this.windowCompt.location.nativeElement);

        this.appRef.attachView(this.contentCompt.hostView);
        this.appRef.attachView(this.windowCompt.hostView);



      }

      public destroyModal(){
        // destroy the component
        // or detach the view
      }

}

我可以创建组件。现在我需要从组件中调用destroy方法,以便在注入domservice时显示循环依赖性错误。

那么如何从创建的组件内部调用destroy方法。

0 个答案:

没有答案