Jan Hommes
Jan Hommes

Reputation: 5152

How to refresh a component on each page change

I am calling a data service in an angular 2 component to load data on the ngOnInit() function. This component is placed on a Ionic tabs page. The ngOnInit() function is only called on initialization, but not on every navigation to the tab. I want to reload data from the data service on each navigation to the page, to refresh the component with the latest data.

How can I call a function in the component on each navigation to a tabs page?

This is my component:

@Component({
  selector: 'reservation-list',
  templateUrl: 'build/components/reservation-list.component.html',
  bindings: [DataService, TimeService]
})
export class ReservationListComponent {
  public items: any = [];

  constructor(private dataService: DataService) { }

  public ngOnInit() {
    // this I want to call on each tab navigation!
    this.items = this.dataService.getEvents();
  }
}

My tabs are basically the ionic2-tabs example:

@Page({
  templateUrl: 'build/pages/tabs/tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = Page1;
  tab2Root: any = Page2;
  tab3Root: any = Page3;
}

And the page is a basic ionic page where the component is insert:

<reservation-list></reservation-list>

@Page({
  templateUrl: 'build/pages/page1/page1.html',
  directives: [ReservationListComponent]
})
export class Page1 {

  constructor() {
  }
}

Upvotes: 1

Views: 2513

Answers (2)

Hkh
Hkh

Reputation: 357

Please follow the life cycle of ionic and use below method inside tab child pages.

ionViewWillEnter()
{
//apply your code
}

This method will call always when you come on page.

Upvotes: 1

Guido
Guido

Reputation: 103

I think you can add a click event handler when you click your tabs and call that function.

In your tag

<a (click)="getEvents()"></a>

In you Component

getEvents() {
    this.items = this.dataService.getEvents();
}

Upvotes: 1

Related Questions