Angular 5 - 如何从DOM中移除动态添加的组件

4
我是一个Angular5的初学者,在我的项目中遇到了以下问题:

我有一个模态框,它始终存在于body中(不活动时隐藏),我在模态框组件中动态生成模态框内容。

问题在于关闭模态框并尝试销毁内容后,内容未从dom中移除,再次打开模态框会将内容附加到现在包含多个元素内容的模态框中。

到目前为止,我已经尝试过多种方法,包括使用具有模板的*ngTemplateOutlet,以及在要放置内容的容器上使用自定义指令,并使用viewContainerRef和componentFactoryResolver动态创建内容组件,可以在此处查看:
Dynamically ADDING and REMOVING Components in Angular

这是我的模态框组件模板(这里的所有代码都是指第二种方法):
<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;
 } 
}

这里是模态框组件的 TypeScript 代码,试图销毁组件的方法在 hideModal 中:

@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]);
 }

到目前为止,我尝试了各种方式,但无法在用户完成后销毁我创建的模态框组件。 显然,我漏掉了什么...
非常感谢您提供任何帮助。

谢谢!

1个回答

3

您可以调用 this.viewContainerRef.detach 方法从容器中移除内容(ViewRef),并保留其引用以备后用。这样做将最终销毁该内容。如果您不想保留其引用,请直接调用 this.viewContainerRef.clear()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接