I have a modal component with this html template:
<div class="modal">
<div class="modal-body">
<ng-content></ng-content>
</div>
<div class="modal-footer">
<button (click)="sendMessage()">success</button>
<button (click)="close()">abort</button>
</div>
</div>
I have an ng-content where I pass a Component in an open function defined into a service:
export class ModalService {
dialogComponentRef: ComponentRef<ModalComponent>;
private subject = new Subject<any>();
open(content: any, obj: any) {
const contentComponentFactory = this.cfResolver.resolveComponentFactory(content);
const modalComponentFactory = this.cfResolver.resolveComponentFactory(ModalComponent);
const contentComponent = contentComponentFactory.create(this.injector);
const modalComponent = modalComponentFactory.create(this.injector,[[contentComponent.location.nativeElement]]);
modalComponent.instance.model = obj;
this.dialogComponentRef = modalComponent;
document.body.appendChild(modalComponent.location.nativeElement);
this.appRef.attachView(contentComponent.hostView);
this.appRef.attachView(modalComponent.hostView);
}
sendMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
close() {
this.appRef.detachView(this.dialogComponentRef.hostView);
}
constructor(
private appRef: ApplicationRef,
private cfResolver: ComponentFactoryResolver,
private injector: Injector
) {}
}
I need to use these modals several times. When I close the button I need to destroy the contentComponent. I see that when I subscribe to sendMessage on the click "SUCCESS" button I see that all the components that I opened subscribed to this next function.
Example, I have this situation. In more than one of my contentComponents I have these subscriptions:
this.mySubscription = this.modalService.getMessage().subscribe( () => {
doing things;
)};
and in the ngOnDestroy I did
this.mySubscription.unsubscribe()
but on the close button nothing happens, I continue subscribing from modal that I just closed. How can I solve this issue?
question from:
https://stackoverflow.com/questions/65831634/angular-how-to-destroy-dynamic-component 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…