Search code examples
ionic-frameworkionic2ionic-view

In Ionic 2, how to pass attribute data between two components?


I have a CheckIn page that has a title attribute.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  templateUrl: 'check-in.html'
})
export class CheckInPage {

  public title: string = 'Check In';
  constructor(public navCtrl: NavController) {
  }
}

I import this page in my TabsPage:

import { Component } from '@angular/core';
import { CheckInPage } from '../check-in/check-in';

@Component({
  templateUrl: 'tabs.html',
})
export class TabsPage {

  public tab3Root: any;

  constructor() {
    this.tab3Root = CheckInPage;
  }
}

And now, I want to use it in my TabsPage view:

<ion-tabs>
  <ion-tab [root]="tab3Root" tabTitle="{{tab3Root.title}}" tabIcon="cog"></ion-tab>
</ion-tabs>

This gives me undefined when I console.log it. Please assist.


Solution

  • There are a few different ways to pass data between pages in Ionic, which are covered in this video: https://www.youtube.com/watch?v=T5iGAAypGBA

    For brevity, I'll only cover one of those ways here: if it's something you want to persist between multiple pages you might do that via an Ionic 2 Provider.

    You can generate a provider in the CLI:

    ionic g provider DemoProvider
    

    It will generate a provider which you can add variables to, like this:

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import 'rxjs/add/operator/map';
    
    /*
      Generated class for the DemoProvider provider.
    
      See https://angular.io/docs/ts/latest/guide/dependency-injection.html
      for more info on providers and Angular 2 DI.
    */
    @Injectable()
    export class DemoProvider {
    
      mySharedVariable: String = "Hello";
    
      constructor() {
      } 
    
    }
    

    In the component where you want to use the provider, make sure you import it, and inject it into the constructor:

    import { Component } from '@angular/core';
    import { DemoProvider } from '../../providers/demoProvider';
    
    @Component({
      selector: 'page-tabs',
      templateUrl: 'tabs.html'
    })
    export class TabsPage {
    
      constructor(public demoProvider:DemoProvider) {
    
      }
      ionViewWillEnter(){
            console.log(demoProvider.mySharedVariable);
      }
    
    }
    

    Hope that helps!