angular 5 - 如何从dom

时间:2017-12-03 16:33:58

标签: angular angular5

我是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>

这是content指令,组件的创建在这里完成:

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

这是模态组件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]);
 }

到目前为止,我已尝试过各种方式,但是在用户完成后,我无法获取我为模态内容创建的组件。显然,我错过了一些东西......任何帮助都将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

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

相关问题