1

I'm trying to add a filter to a filters popup built in bootstrap modal (ngx-bootstrap), but I face the following issue: My options array looks like

[
   {
      "name":"All",
      "value":""
   },
   {
      "name":"Foo",
      "value":"foo"
   },
   {
      "name":"Bar",
      "value":"bar"
   },
]

template:

    <ng-select
      (change)="updateFilter($event)"
      [(ngModel)]="value">
      <ng-option *ngFor="let option of options"
                 [value]="option.value">
        <div title="{{option.name}}">{{option.name}}</div>
      </ng-option>
    </ng-select>

@ng-select/ng-select v.7

When the popup is rendered and select options are shown up I can't select an option on mouse click. I can select an option using my arrow keys and pressing Enter, I can hover over the elements and they are highlighted. But when I click, it does nothing, no events, no js errors in console, nothing.

I can only guess that something else is interfering with the click event on my page, but I don't know how to find it.

Note: I have tried adding appendTo="body" - no luck

UPD: the simple trackBy solved my issue.

user3841429
  • 326
  • 2
  • 15
  • Can you please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) on an online IDE like [Stackblitz](https://stackblitz.com). – Siddhant Feb 26 '22 at 07:23
  • I'm getting filter options from an API endpoint and passing them to the modal right after getting it. I found this a useful comment here: https://stackoverflow.com/a/58621500/3841429 and tried to pass a static array and it works just fine. But the provided solution is not working for me. But, at least, I know the core of my problem. – user3841429 Feb 28 '22 at 04:38
  • Here is my lifesaver comment: https://stackoverflow.com/a/45391247 – user3841429 Feb 28 '22 at 05:06
  • Sounds like you fixed your problem.. could you please add an answer to this question with your fix, and mark it as accepted so that this question is marked as resolved? Thanks :) – Zze Feb 28 '22 at 05:36

1 Answers1

1

The solution was simple: How to use `trackBy` with `ngFor` I added the trackBy function that preserves the value of the ng-select element:

    <ng-select
      (change)="updateFilter($event)"
      [(ngModel)]="value">
      <ng-option *ngFor="let option of options; trackBy:identify"
                 [value]="option.value">
        <div title="{{option.name}}">{{option.name}}</div>
      </ng-option>
    </ng-select>
  identify(index, item){
     return item.name; 
  }
user3841429
  • 326
  • 2
  • 15