Pages

How to Pass Data from One Component to Another Component without Navigating to the Other Page.


You May have alread Come or may Come Across situation when building your ionic mobile application, where you’ll probably want to fire an event in one of your component and have that event handled in another component. To tackle this Ionic 2 has provided us with "Events", which allows you to Subscribe to an event in one component, that have been Published in another component. Once the Event is Published it can be Subscribed on multiple Components. This Post explain's on how to publish an Event and also Subscribe to it. first, as usual create an ionic project
Copy and paste the below command

ionic start ExampleProject sidemenu --v2
it can be blank or tabs project your wish.. next, create a Component with name "changes" as follows.
Copy and paste the below command

ionic generate page changes
after the component is created, import the page in app.modle.ts

   import { ChangesPage } from '../pages/changes/changes';
next, add "ChangesPage" to NgModule's declarations as well as bootstrap's entryComponents. after modifying, app.module.ts will look something like this.

 import { BrowserModule } from '@angular/platform-browser';
 import { ErrorHandler, NgModule } from '@angular/core';
 import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

 import { MyApp } from './app.component';
 import { HomePage } from '../pages/home/home';
 import { ListPage } from '../pages/list/list';
 import { ChangesPage } from '../pages/changes/changes';

 import { StatusBar } from '@ionic-native/status-bar';
 import { SplashScreen } from '@ionic-native/splash-screen';

 @NgModule({
   declarations: [
     MyApp,
     HomePage,
     ListPage,
     ChangesPage
   ],
   imports: [
     BrowserModule,
     IonicModule.forRoot(MyApp),
   ],
   bootstrap: [IonicApp],
   entryComponents: [
     MyApp,
     HomePage,
     ListPage,
     ChangesPage
   ],
   providers: [
     StatusBar,
     SplashScreen,
     {provide: ErrorHandler, useClass: IonicErrorHandler}
   ]
 })
 export class AppModule {}

Now open changes.html file in changes foder.
Copy and paste the below code

 <ion-content>
     <ion-list>
       <ion-item *ngFor="let item of list">
       <ion-grid>
       <ion-row>
          <ion-col col-2>
            {{item.id}}
         </ion-col>
         <ion-col col-8>
           {{item.name}}
         </ion-col>
       </ion-row>
  </ion-grid>       
       </ion-item>
     </ion-list>
</ion-content>
Open changes.ts file and paste the below ts code.
Copy and paste the below ts code

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


 @Component({
   selector: 'page-changes',
   templateUrl: 'changes.html',
 })
 export class ChangesPage {
   list:any=[];
   constructor(public navCtrl: NavController, public navParams: NavParams,public events: Events) {
    this.list = [{name:"vinay",id:1},{name:"kumar",id:2},{name:"ravi",id:3},{name:"naveen",id:4}]
     this.events.subscribe('userObj',data => {
     let mydata = data;
     this.list.push(mydata);
     console.log("list",this.list)
     this.myalert(mydata);
   });
   }

   ionViewDidLoad() {
     console.log('ionViewDidLoad ChangesPage');
   }

   myalert(mydata){
    alert('Added new record with name '+mydata.name+' &with id '+mydata.id);
   }
  
 }

Since our work in changes Component is over lets head over to home page. open home.html and replace the html with below html code.
Copy and paste the below html code

 <ion-header>
   <ion-navbar>
     <button ion-button menuToggle>
       <ion-icon name="menu"></ion-icon>
     </button>
     <ion-title>Home</ion-title>
   </ion-navbar>
 </ion-header>

 <ion-content padding>
   <ion-item>
     <ion-label color="primary" floating>Name</ion-label>
     <ion-input [(ngModel)]="Obj.name" ></ion-input>
   </ion-item>

   <ion-item>
     <ion-label color="primary" floating>Id</ion-label>
     <ion-input [(ngModel)]="Obj.id" ></ion-input>
   </ion-item>

    <button ion-button full secondary  (click) = "addObject(Obj)">Add User</button>
    <page-changes></page-changes>
 </ion-content>

next replace code in you home.ts with the below code
Copy and paste the below ts code

 import { Component } from '@angular/core';
 import { NavController, NavParams } from 'ionic-angular';
 import { Events } from 'ionic-angular';
 import { ChangesPage } from '../changes/changes';

 @Component({
   selector: 'page-home',
   templateUrl: 'home.html'
 })
 export class HomePage {

   Obj:any = {name:"",id:0};
     constructor(public navCtrl: NavController, public navParams: NavParams,public events: Events) {
   }

   ionViewDidLoad() {
     console.log('ionViewDidLoad EventsPage');
   }

   addObject(Obj) {
     this.events.publish('userObj',Obj);
     this.Obj = {name:"",id:0}
   }

 }

run the project now, you can see that the record you entered in the input will be updates in other component.
Code Explanation
In home.html i've added "" element at the bottom, which is of ChangesPage Component's selector. what this does is it displays the ChangesPage view here in HomePage Component. to use Events we need to import Events class so, In home.ts i've impoerted the class ie:

  import {Events} from ‘ionic-angular‘;
  ...
  constructor(public events: Events) { }

"this.events.publish" is used to publish, so i've used "userObj" as publish name and send the data object "obj" when new record is entered when addObject() method is called.

   addObject(Obj) {
     this.events.publish('userObj',Obj);
     this.Obj = {name:"",id:0}
   }

since we have published the event all is left is to subscibe to the event where we want the changes to take place. so in this example i've subscribed to event in ChangesPage component to push the record in list object. "this.events.subscribe" is used to subscribe to an event.

   this.events.subscribe('userObj',data => {
     let mydata = data;
     this.list.push(mydata);
     console.log("list",this.list)
     this.myalert(mydata);
   });;

vinay kumar

Founder of Gowriter.Blogspot.com, Tech Enthusiast, Normal type of Person with passion toward's work.

2 comments:

Anonymous said...

Thank you..it helped..

Anonymous said...

nice..worked great..