【发布时间】: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()">×</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]);
}
到目前为止,在我尝试过的所有方式中,我都无法在用户完成后销毁我为模态内容创建的组件。显然,我遗漏了一些东西...
任何帮助将不胜感激。
谢谢!
【问题讨论】: