How to position a popover in Ionic 2

Schlaus picture Schlaus · Nov 10, 2016 · Viewed 19.4k times · Source

How do I manually position a popover in Ionic 2?

I can't set the position in a css class, since the popover controller sets the position with an inline style.

Answer

Schlaus picture Schlaus · Nov 10, 2016

Looking through the code, there doesn't seem to be an option for the popover's position. However, when opening the popover as a result of the user tapping something, it can be positioned by the click event. We can use that knowledge for manual positioning as well:

let pop = this.popoverCtrl.create(MyPopover);

let ev = {
  target : {
    getBoundingClientRect : () => {
      return {
        top: 100
      };
    }
  }
};

pop.present({ev});

A few things to note:

  • You can set the value for top, left, or both.
  • The values must be given in pixels, as numbers.
  • If top or left is not given, then the usual positioning algorithm is used for that value.

I'd be happy to know if there's a better way, but so far this is the best I could come up with.

This certainly works in Ionic2 and 3, happy to have someone confirm if it works in Ionic4 as well!