krv
krv

Reputation: 2920

Ionic 3: Passing Data when Setting the root page

I am checking some localstorage info and depending on the info I get I want to load the appropriate page.

So in my app.component.ts I have the following.

export class MyApp {
  rootPage: string;

 constructor(){
  if(dataFound)
   this.rootPage="HomePage"
  else
   this.rootPage="OtherPage"
  }
}

Is there a way I can pass data when setting the this.rootPage.

Keep in mind that this is the initial load of the app. If this happen after the app has loaded I can do this.navCtrl.setRoot() which will allow me to pass parameters along with the page.

Any help is appreciated.

Thanks

Upvotes: 5

Views: 5620

Answers (5)

Alessandro Ornano
Alessandro Ornano

Reputation: 35392

IONIC 3:

So, starting from the page where you want to set OtherPage as the new root page you can write:

let rootPageParams = {'currentClusterID': 2 }
this.app.getRootNav().setRoot(OtherPage, rootPageParams);

Then, in OtherPage:

ngOnInit() {
     let currentClusterID = this.navParams.get('currentClusterID');
     console.log('# OTHER PAGE: currentClusterID', currentClusterID);
}

If you want to use html template to set your root instead of typescript you can write:

.TS:

rootPage: any = OtherPage;
currentClusterID: number = 2;

.HTML:

<ion-nav 
    main #content 
        [root]="rootPage" 
        [rootParams]="{'currentClusterID':currentClusterID}">
</ion-nav>

Upvotes: 3

Duveral
Duveral

Reputation: 335

As @gaborp said, but with a little difference :

  1. In your root:

    <ion-nav [root]="rootPage" [rootParams]="rootPageParams"></ion-nav>

    this.rootPageParams = {'username': "David" }

  2. In the view you want to read that param (this is the difference):

    this.username = this.nav['rootParams'].username;

All I read was about tabs, but nothing for a simple ion-nav, so that is the way I did it.

Upvotes: 7

deepak thomas
deepak thomas

Reputation: 1180

You can place getter and setter function for the MyApp which can be accessed by other component when you import MyApp component in it, by which you can pass data between component

Or you could pass it from parent to child or vice versa using @input and @outputemitter

Or use an Observable decorator service in order to communicate between services

Upvotes: 0

gaborp
gaborp

Reputation: 714

Also you can use NavParams:

this.rootPageParams = { id: "123", name: "Carl" };

<ion-nav [root]="rootPage" [rootParams]="rootPageParams"></ion-nav>

Then access the params from your root page:

let id = navParams.get('id'); let name = navParams.get('name');

Upvotes: 6

Gulam Mohammed
Gulam Mohammed

Reputation: 25

Have a look at Events section in Ionic Docs.

You will be able to pass your data (if found) to your OtherPage from the RootPage by simply going through the same.

You can also have a look at this answer given by @sebaferreras for more understanding

Happy Coding!

Upvotes: 0

Related Questions