Reputation: 1433
In my Ionic/Angular app I have a situation where I load a modal and then, when the modal closes, I re-load my main component. The problem I was running into is that, based on the way Angular handles component loading, this action wouldn't actually make my main component re-load/re-mount. It would simple show the component in the state as it existed on the stack. This didn't work in my use case, because I need to re-load the component in order for some logic to run to update data that just changed based on what happened in the modal.
I found a way to handle this, but it feels pretty hacky. Basically upon modal close I call a service like so:
async closeModal() {
await this.modalCtlr.dismiss();
this.navService.navigateHome();
}
And in my service function I would basically tack on an incremented value so to force the component to re-load, like so:
navigateHome() {
const incCount = this.counter += 1;
this.navCtlr.navigateRoot(`/main/${incCount}`);
}
This works, but, as I say, it feels pretty hacky. Is there a built-in Angular way of handling this - to ensure that the component re-loads when an event such as the closing of a modal happens?
Upvotes: 1
Views: 871
Reputation: 6289
You mentioned this being an Ionic/Angular project. That being the case, Ionic has some additional baked-in functions than can be helpful in exactly these kinds of scenarios.
In your use case the ionViewWillEnter()
would likely resolve the issue. This goes in your main component file. All you need to do is call the function(s) you need to load within there, like so:
runUpdateLogic() {
// do something necessary here
}
ionViewWillEnter() {
this.runUpdateLogic();
}
Note, to use this implementation you'll also want to use Ionic's navController
to navigate back to you main component, which I see you're already using. Now it would just look like this:
async closeModal() {
await this.modalCtlr.dismiss();
this.navCtlr.navigateRoot(`/main`);
}
This works because, even though in your use case Angular's ngOnInit()
will not fire in your main component when the modal closes, Ionic's ionViewWillEnter()
will.
Upvotes: 1
Reputation: 3593
Move your component initialization code to a separate method, and when you modal closes, call that method again.
For example, if you had something like this:
ngOnInit() {
this.data = somethingFromAService();
this.someOtherVar = "cool";
}
Change to this
initComponent() {
this.data = somethingFromAService();
this.someOtherVar = "cool";
}
ngOnInit() {
this.initComponent();
}
callSomeModal() {
// assumes the modal has some sort of promise it returns on close, I'm just guessing because there was no example code
modal.open().then(returnValue => {
this.initComponent();
})
}
Upvotes: 1