How to position a popover in Ionic 2

2019-03-10 23:35发布

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.

4条回答
叛逆
2楼-- · 2019-03-10 23:56

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.

查看更多
叼着烟拽天下
3楼-- · 2019-03-10 23:59

if you want the popover next to te button, pass to the function create() the event, like this

//home.html

<button ion-button icon-only (click)="presentRadioPopover($event)">
        <ion-icon name="more"></ion-icon>
 </button>

//home.ts

 presentRadioPopover(event) {
    const popover = this.popoverCtrl.create(HomepopoverPage);
    popover.present({
      ev: event
    });
  }
查看更多
仙女界的扛把子
4楼-- · 2019-03-11 00:01

Though the above code works for some people, but I found a better solution where passing the cssClass on popover.

To make use of the cssClass, you must declare it globally in app.scss as shown below:

.custom-popover .popover-content {
  width: 80%;
  top: 70px;
  left: 30px;
  bottom: 70px
}

In your .ts file, you can pass the class like below:

let popover = this.popoverCtrl.create(PopoverPage, {}, {cssClass: 'custom-popover'});

popover.present();

查看更多
放荡不羁爱自由
5楼-- · 2019-03-11 00:01

If you only want to change the placement of the popover relative to the pressed element, CSS transformations might help. E.g. to place it to the top-right / left-bottom of the clicked element, instead of default bottom-right corner.

Add cssClass option:

let popover = this.popoverCtrl.create(PopoverPage, {}, {cssClass: 'popover-top-right'});

popover.present({
  ev: event
});

and use the following CSS somewhere:

.popover-top-right .popover-content {
  transform: translateY(-120%) !important;
}

This solution is somewhat like Mnemo suggested, but more generic as you don't need to specify fixed coordinates. Though it's not that customizable as the accepted workaround from Schlaus.

This way you can use translateXY(-100%, -100%) to put the popover to the left-top corner, etc. The !important is perhaps needed to override ionic styles (or use more specific CSS selector instead).

查看更多
登录 后发表回答