'Close active modal
I have opened multiple modals in my angular project. I have made a modal component as wrapper for the content. Now I want to close the active modal instead of closing all modals. So the dismissAll need to be replaced. I have in mind to use NgbActiveModal but get an error as soon as I add this to the constructor.
The error message as appears in the browser
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NgbActiveModal -> NgbActiveModal -> NgbActiveModal]: NullInjectorError: No provider for NgbActiveModal! NullInjectorError: R3InjectorError(AppModule)[NgbActiveModal -> NgbActiveModal -> NgbActiveModal]: NullInjectorError: No provider for NgbActiveModal!
How to solve this?
My code
import {Component, ElementRef, Input, ViewChild} from '@angular/core';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
import {faTimes} from '@fortawesome/free-solid-svg-icons';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.scss']
})
export class ModalComponent {
@Input() titel: string = 'Editor';
@Input() popupClass: string;
@ViewChild('content') content: ElementRef;
cross = faTimes;
constructor(private modalService: NgbModal,
private activeModal: NgbActiveModal) {
}
open() {
this.modalService.open(this.content,
{ ariaLabelledBy: 'modal-basic-title',
windowClass: this.popupClass
}).result.then((result) => {}, (reason) => {
});
}
close() {
this.modalService.dismissAll()
}
}
Solution 1:[1]
You should keep a ref to the currently opened modal and close only that one:
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.scss']
})
export class ModalComponent {
@Input() titel: string = 'Editor';
@Input() popupClass: string;
@ViewChild('content') content: ElementRef;
cross = faTimes;
private modalRef: any;
constructor(private modalService: NgbModal) {
}
open() {
this.modalRef = this.modalService.open(this.content,
{ ariaLabelledBy: 'modal-basic-title',
windowClass: this.popupClass
}).result.then((result) => {}, (reason) => {
});
}
close() {
this.modalService.close(this.modalRef);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Octavian Mărculescu |