【问题标题】:angular 5 - how to remove dynamically added components from the dom角度 5 - 如何从 dom 中删除动态添加的组件
【发布时间】:2018-05-17 03:55:10
【问题描述】:

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

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

问题是,在关闭模态并尝试销毁内容后,内容并没有从 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;
 } 
}

这里是modal组件的ts代码,试图销毁组件是在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]);
 }

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

谢谢!

【问题讨论】:

    标签: angular angular5


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 2018-07-03
      • 2021-01-17
      • 2018-09-15
      • 1970-01-01
      • 2019-08-21
      • 2020-04-05
      • 2020-04-06
      • 1970-01-01
      相关资源
      最近更新 更多