Popover Callback not working as expected?

Hello Ionic Comunity,

i am relatively new to Ionic 2, but familiar with AngularJS and Angular2.

I want to create a popover with dynamic buttons, to get a reusable popover component.

The popover looks like:

 @Component({
  template: `<ion-list class="popover-list">
          <button ion-item *ngFor="let action of actions" (click)="action.callback()">{{action.title}}</button>
        </ion-list>
        `
})
 export class PopoverComp {
   actions: any;
   constructor(private viewCtrl: ViewController, private navParams: NavParams) {
     this.actions=navParams.data.actions;
   }
 }

The Popover is called via:

  presentPopover(ev) {
    let popover = this.popoverCtrl.create(PopoverComp, {
      actions: [
        {
          title: 'Report Circle',
          callback: this.reportCircle
        }
      ]
    });

    popover.present({ev: ev});
  }

  reportCircle() {
    console.log("report", this.reportService);
    this.reportService.reportCircle('a','b','c');
  }

Problem is, that the reportService is undefined as soon as it is called from outside of the original component.
the console.log in reportCircle() says “report” undefined

I expected the callback to be executed in the scope of the component which called the popover. Or how should it be possible to:

Present a list of actions to perform inside one of your views

Any help is appreciated.

I’d try changing:

    let popover = this.popoverCtrl.create(PopoverComp, {
      actions: [
        {
          title: 'Report Circle',
          callback: this.reportCircle
        }
      ]
    });

to:

    let popover = this.popoverCtrl.create(PopoverComp, {
      actions: [
        {
          title: 'Report Circle',
          callback: () => { this.reportCircle(); }
        }
      ]
    });

That way the proper context will/should be maintained.

2 Likes