Reputation: 31
I'm new to both Ionic and Angular and have been struggling to find the solution to my problem. I got a particular function I'd like to call present on a certain page file. I need to call this function from a button component file (in order to execute it on click). I was wondering how to do this as I've tried looking for a solution but can't find one and I can't just copy the function as this reloads some data that needs to be updated in the page. Thank you in advance.
Function on settings.page.ts (the page that contains the function):
loadData() {
this.storageService.getData().then(datas=> {
if (datas) {
this.datas = datas;
for(let data of datas) {
this.average = this.average + (data.value / data.total);
}
this.average = (this.average / datas.length);
this.average100 = this.average * 100;
}
});
Where I need to call the function on new-button.component.ts:
async showPopover( event ) {
const popover = await this.popoverCtrl.create({
component: NewComponent,
event: event,
mode: 'ios'
});
await popover.present();
}
Upvotes: 0
Views: 963
Reputation: 2663
For this specific need, you first need to understand how components communication work in angular.
In angular components are well-defined, encapsulated units that can communicate with other components but through proper organized manner, not just randomly one components calling methods of other component.
You've got a couple of options
1.) You could introduce EventEmitters in your calling component and listen to that event in the component that you want to run method on.Provided that your components are linked (parent -> child relationships)
2.) You could move the common code loadData() method in your case to an @Injectable service and using Dependency Injection introduce it in the new-button.component.ts file.
3.) You can use RxJS Subjects, call the next method of subject on the button click and this would get listened in any component that has subscribed to the subject.
Please find these few links on the topic
https://dzone.com/articles/understanding-output-and-eventemitter-in-angular
https://medium.com/@manivel45/event-emitter-vs-subject-cross-component-communication-8934376605e1
https://netbasal.com/event-emitters-in-angular-13e84ee8d28c
Thanks.
Upvotes: 1