Vasilis Greece
Vasilis Greece

Reputation: 907

Ionic 3 run function from root page in child page

Working with Ionic 3.

root page app.component.ts:

...
export class MyApp {
  @ViewChild('myNav') nav: NavController
  rootPage:any = HomePage;
  sdata = [];
  getListName(){
    //returns an array a list for menu names 
   //sdata
  }
}

app.html:

<ion-menu [content]="content">
  <ion-header>
    <ion-toolbar>
      <ion-title>Μενού</ion-title>
    </ion-toolbar>
  </ion-header>

<ion-content>
  <ion-list>
    <button menuClose ion-item class="menulist elvtitles" *ngFor="let p of sdata" (click)="toElevator(p.elevatorID)">
      <ion-icon name="construct"></ion-icon> {{p.address}}
     </button>
  </ion-list>
</ion-content>

</ion-menu>
<ion-nav #myNav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

Now what I want is to run again the function getListName from a page (child). In order my list getting refreshed. Like:

export class ChildPage {
  refresh(){
   this.getListName()
  }
}

What I have tried so far is to use Output method but this below is not working:

export class ChildPage {
  @Output() intervalFired = new EventEmitter<any>();  
  refresh(){
     ...
     this.intervalFired.emit(dataAll);
  }
}

and in app.html:

<child-register (intervalFired)="onIntervalFired($event)"></child-register>

or

<button (intervalFired)="onIntervalFired($event)" menuClose ion-item class="menulist elvtitles" *ngFor="let p of sdata" (click)="toElevator(p.elevatorID)">
        <ion-icon name="construct"></ion-icon> {{p.address}}
      </button>

but nothing is working.

What I need is to call the parent (app.component) function in my child page with some way. I guess my problem is clear, if not ask me for details. Any ideas or directions will be appreciated.

Upvotes: 0

Views: 251

Answers (1)

Wasiq Muhammad
Wasiq Muhammad

Reputation: 3118

There are two Approaches

  1. Create a Service and inject or use in your both App (Parent) and Child Component.
  2. Use Events (Pub/Sub) Method

Example

Child Page

import { Events } from 'ionic-angular';

export class ChildPage {

    constructor(public events: Events) {}
    ChildPage() {
      console.log('Child Page!')
      this.events.publish('menu:update');
    }
}

App/Parent Page

import { Events } from 'ionic-angular';

export class MyApp {

    constructor(public events: Events) {
      events.subscribe('menu:update', () => {
         this.getListName()
      });
    }
  @ViewChild('myNav') nav: NavController
  rootPage:any = HomePage;
  sdata = [];
  getListName(){
    //returns an array a list for menu names 
   //sdata
  }
}

Upvotes: 1

Related Questions