Search code examples
angulardropdownngx-bootstrap

ngx-bootstrap dropdown alignment not working when setting dynamic class


I have an odd issue with the ngx-bootstrap (using bootstrap 4.1) dropdown component.

I'm setting the dropdown menu to align to the right via a variable, however, when I do this the dropdown only aligns right on the second click.

Here is a sample code that replicates the issue:

<div class="btn-group" dropdown placement="bottom right">
    <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">
      This dropdown's menu is right-aligned <span class="caret"></span>
    </button>
    <ul *dropdownMenu class="dropdown-menu" [ngClass]="{'dropdown-menu-right': true}" role="menu">
      <li role="menuitem"><a class="dropdown-item" href="#">Action</a></li>
      <li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
      <li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
      <li class="divider dropdown-divider"></li>
      <li role="menuitem"><a class="dropdown-item" href="#">Separated link</a></li>
    </ul>
</div>

Note: the [ngClass] where I'm dynamically setting the attribute is what is causing the issue, if I put this statically in the class definition it works fine.

Here is a sample Plunker that replicates: https://plnkr.co/edit/5OrrQx0uefrWxWBliJDL?p=preview


Solution

  • If you look at the generated html in the debugger, you'll see that the ul contains your dropdown-menu-right class AND some inline styles, which override the positionning (the first time you open it). These inline styles are probably added by the library.

    <ul class="dropdown-menu show dropdown-menu-right" 
    role="menu" ng-reflect-klass="dropdown-menu" 
    ng-reflect-ng-class="[object Object]" 
    style="left: 0px; right: auto; top: 100%; transform: translateY(0px);">
    

    Maybe you should take the issue to github with the library maintainers. As a workaround, you could try adding this css to your global CSS file

    .dropdown-menu-right {
        right: 0 !important;
        left: auto !important; 
    }
    

    This is the same style defined by default for that class, except that there is the important rule

    Your plunker edited (with style in index.html)