Search code examples
angularprimengprimeng-dropdowns

Primeng dropdown prevent overlay close on item select and update the options


I'm trying to update the list of options in dropdown after click the "-More-" option. I get it work with template for options and binding click event I prevent it stopPropagation() func.

<ng-template let-city pTemplate="item">
  <span (click)="onClickFunction(city, $event)">{{city.label}}</span>
</ng-template>

onClickFunction(city, e) {
  if (city.label === '-More-') {
    this.cities.pop();
    this.cities = [...this.cities, ...this.newCities];

    e.stopPropagation();

    this.cd.markForCheck();
    this.cd.detectChanges();
  }
}

But the problem is that sometimes it works from the first load, but usally I click 3 times on "-More-" option and then it works correctly. I this a bug or I'm doing it wrong? maybe there is another better solution? Thanks

https://stackblitz.com/edit/primeng-dropdown-demo-j6te3c


Solution

  • So I found the problem why this sometimes didn't work.

    the <span> with (click) event binded is way smaller than the box wrapped higher (<li>), so when clicked exactly on span this works, if you click a little right to the text option "-More-" than it wouldn't work.

    The solution for me is to use <div> instead of <span> and override the default padding with negative margins and add the exact padding for that

    code:

    <ng-template let-city pTemplate="item">
      <div class="option" (click)="onClickFunction(city, $event)">{{city.label}}</div>
    </ng-template>
    
    div.option {
      margin: -0.429em -0.857em;
      padding: 0.429em 0.857em;
    }