Reputation: 1726
I have a page that can be navigated to by more than one "parent/origin" page.
Something like this:
Page 1 \
\
Page 2 -- Page 4
/
Page 3 /
I need to return some data from Page 4 to it's parent (the origin page).
I've been using this.navCtrl.back()
to navigate back on the rest of the application, but this time I need to return some data and it seems that it is not possible using this function.
I know it is possible to pass data using this.navCtrl.navigateBack(['page-1'], extras)
, but I would need to know which page the user came from. Is there any easy way of doing this?
I know I can pass the name of the origin page on the extras when going to Page 4, but it doesn't seem so correct (what is your opinion?).
Thanks in advance.
Upvotes: 3
Views: 236
Reputation: 76679
Already pass the origin as extras when navigating forward - then it will be known on page 4 and can be used to return extras to a specific page. It's pretty simple and does not require a modal dialog workaround, which had not been asked for.
Upvotes: 3
Reputation: 44659
As I was saying in the comments, this looks like the perfect scenario to use modals. That way Page 4
could return data to the caller even without knowing what page has created/presented it.
The code could be something like this:
Page 1 / Page 2 / Page 3:
// Angular
import { Component } from '@angular/core';
// Ionic
import { ModalController, OverlayEventDetail } from '@ionic/angular';
// Modal page
import { ModalPage } from '../modal/modal.page';
@Component({ ... })
export class ModalExample {
constructor(public modalController: ModalController) {}
async presentModal() {
// create the modal
const modal = await this.modalController.create({
component: ModalPage,
componentProps: {
'firstName': 'Douglas',
'lastName': 'Adams',
'middleInitial': 'N'
}
});
// handle the data returned by the modal
modal.onDidDismiss().then((detail: OverlayEventDetail) => {
if (detail !== null) {
console.log('The result: ', detail.data);
}
});
// present the modal
return await modal.present();
}
}
Page 4
// Angular
import { Component, Input } from '@angular/core';
// Ionic
import { NavParams } from '@ionic/angular';
@Component({ ... })
export class ModalPage {
// Data passed in by componentProps
@Input() firstName: string;
@Input() lastName: string;
@Input() middleInitial: string;
constructor(navParams: NavParams) {
// componentProps can also be accessed at construction time using NavParams
console.log(navParams.get('firstName');
}
dismiss() {
// using the injected ModalController this page
// can "dismiss" itself and optionally pass back data
this.modalCtrl.dismiss({
'dismissed': true
});
}
}
Please make sure to go through the lazy loading section from the Ionic Docs to see how the modal page should be imported by the pages that are going to use it.
Upvotes: 3