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?
The error means that one of the items in the array being displayed is null
. To solve this, filter null
s 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))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With