Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property '$ngoptionlabel' of null when using ng-select

I'm using ng-select to display data which my app has retrieved from an API, but although the data is successfully retrieved nothing is shown in the dropdown. It just says "No items found." In the console I have the following error:

ERROR TypeError: Cannot read property '$ngoptionlabel' of null

This is my typescript code:

// in a service, using HttpClient
this.http.get<string[]>(url);
// in a component, using the service injected in
data: string[] = [];
this.service.get()
   .subscribe(data => {
      this.data = data; // data contains values as expected
      // other logic
   });

In my template, I pass this.data to ng-select.

<ng-select [items]="data"
           [multiple]="true"
           [closeOnSelect]="false"
           [searchable]="true">
</ng-select>

I thought the error sounded like it might be to do with the bindLabel option, but I'm not using it. What does the error mean, and how can I fix it?

like image 850
Tim Avatar asked Jul 16 '20 11:07

Tim


Video Answer


1 Answers

The error means that one of the items in the array being displayed is null. To solve this, filter nulls out of the array before passing it to ng-select. In the case where the data is being retrieved from an API, you can use the rxjs map operator to achieve this.

this.http
   .get<string[]>(url)
   .pipe(
      map(data => data.filter(x => x != null))
   );
like image 133
Tim Avatar answered Sep 30 '22 18:09

Tim