angular 5-如何从dom中删除动态添加的组件

angular 5-如何从dom中删除动态添加的组件,angular,angular5,Angular,Angular5,我是Angular 5的初学者,在我的项目中遇到了以下问题:我有一个模态,它总是出现在主体上(不活动时隐藏),我在模态组件中动态生成模态的内容问题是,在关闭模式并尝试销毁内容后,内容不会从dom中删除,再次打开模式只是将内容附加到模式中,该模式现在包含内容的多个元素。到目前为止,我尝试了几种方法,包括使用带有模板的*ngTemplateOutlet,另外,在我想要放置内容的容器上有一个自定义指令,并使用viewContainerRef和componentFactoryResolver动态创建内容

我是Angular 5的初学者,在我的项目中遇到了以下问题:

我有一个模态,它总是出现在主体上(不活动时隐藏),我在模态组件中动态生成模态的内容

问题是,在关闭模式并尝试销毁内容后,内容不会从dom中删除,再次打开模式只是将内容附加到模式中,该模式现在包含内容的多个元素。

到目前为止,我尝试了几种方法,包括使用带有模板的*ngTemplateOutlet,另外,在我想要放置内容的容器上有一个自定义指令,并使用viewContainerRef和componentFactoryResolver动态创建内容组件,如图所示:


这是我的模态组件的模板(这里的所有代码都指第二种方法):


到目前为止,我尝试过的所有方法都无法在用户使用完为模态内容创建的组件后将其销毁。显然,我错过了一些东西……
任何帮助都将不胜感激。

谢谢

您可以调用
this.viewContainerRef.detach
从容器中删除内容(ViewRef),并保留对is的引用以备以后使用。这最终将被摧毁。如果您不想保留对它的引用,只需调用
this.viewContainerRef.clear()

<div class="modal-backdrop show" (click)="hideModal()"></div>
 <div class="modal-dialog show">
  <div class="modal-content">
   <ng-container content></ng-container>
   <button type="button" class="close" data-dismiss="modal" 
     (click)="hideModal()">&times;</button>
  </div>
 </div>
@Directive({
  selector: '[content]'
 })
export class ContentDirective {
  constructor(
    public viewContainerRef: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) {}

createModalContent(content: { new (): Component }): ComponentRef<{}> {
  const sample = this.viewContainerRef;
  this.viewContainerRef.clear();
  const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
  content);
  const componentRef = this.viewContainerRef.createComponent(componentFactory);
  return componentRef;
 } 
}
@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css'],
  entryComponents: [SuggestSkillComponent]
})

export class ModalComponent implements OnInit {

newComponent: ComponentRef<{}>;
@Input() opened: boolean;
@Input() modalType: string;
@ViewChild(ContentDirective) content: ContentDirective;
modalState: string;
subscription: any;

constructor(private modalService: ModalService) {}

hideModal() {
  this.modalService.closeModal();
  this.newComponent.destroy();
}

ngOnInit() {
   this.subscription = this.modalService.getModalState()
   .subscribe(([modalState, modalContent]) => {
    if (modalState === 'shown') {
      this.newComponent = this.content.createModalContent(modalContent);
    }
  });
 }
}
 openModal(content: any) {
  this.modalOpened = true;
  this.modalState = 'shown';
  this.emitter.emit([this.modalState, content]);
 }