I've tried different ways to get the component instance after creating a modal using ionic and angular, however nothing worked for me. Could you please help me to understand, how can I get a component instance reference after creting a modal? The sample code is listed below:
const modal = await this.modalController.create({
component: MyCustomComponent,
cssClass: "some-css-class",
componentProps:
{
item: item
},
backdropDismiss: false
});
modal.canDismiss = async (data?: any, roleDismiss?: string) => {
let can = false;
return new Promise<boolean>(resolve => resolve(can));
}
for example, in the canDismiss handler I'd like to verify some actual component instance properties, however I can't seem to find a proper way of doing this. How can I access the MyCustomCompnent instance after creating the modal?
I'm using ionic angular 8, angular 18.1.3
create service that used for communicate between modal and parent component
export class ModalService {
private modalInstanceSubject = new BehaviorSubject<any>(null);
modalInstance$ = this.modalInstanceSubject.asObservable();
setModalInstance(instance: any) {
this.modalInstanceSubject.next(instance);
}
}
In MyCustomComponent
, inject ModalService
and set instance of the component
export class MyCustomComponent implements OnInit {
constructor(private modalService: ModalService) {}
ngOnInit() {
this.modalService.setModalInstance(this);
}
// Example property you want to access
someProperty: boolean = false;
}
In parent component where you create modal, inject ModalService
and subscribe to modalInstance$ to get instance of the modal
export class ParentComponent {
constructor(private modalController: ModalController, private modalService: ModalService) {}
async openModal() {
const modal = await this.modalController.create({
component: MyCustomComponent,
cssClass: 'some-css-class',
componentProps: {
item: 'some item'
},
backdropDismiss: false
});
modal.present();
this.modalService.modalInstance$.subscribe(instance => {
if (instance) {
// Now you can access the instance of MyCustomComponent
console.log(instance.someProperty);
modal.canDismiss = async (data?: any, roleDismiss?: string) => {
// Access the component instance properties here
return instance.someProperty;
};
}
});
}
}