Best way to check for null values using *ngFor in Angular 2
Nevermind - this checks if the array is null, not elements within the array.
Instead of the custom pipe, you could just do a null check right in the *ngFor
, I think it's pretty readable. You're just providing an empty array if performances
is null:
<tr *ngFor="let performance of (performances ? performances : [])">
UPDATED on 03.01.2020
There are multiple ways.
Using only the template:
- use empty array (or maybe some fallback array) if its undefined or null..:
<tbody>
<tr *ngFor="let performance of (performances || [])">
<td>{{ performance.id }}</td>
...
</tr>
</tbody>
- check it inline and use a default value:
<tbody>
<tr *ngFor="let performance of performances">
<td>{{ performance?.id || 1337 }}</td>
...
</tr>
</tbody>
- you could use *ngIf:
<tbody>
<tr *ngFor="let performance of performances">
<td *ngIf="performance?.id; else elsePerfId">{{ performance.id }}</td>
<ng-template #elsePerfId>
<td>default</td>
</ng-template>
...
</tr>
</tbody>
- using a pipe and returning a default value:
<tbody>
<tr *ngFor="let performance of (performances | defaultValueIfNullPipe)">
<td>{{ performance.id }}</td>
...
</tr>
</tbody>
Using Component..
You could also take care that there are no invalid values:
getFunds(){
this._service.getData().then(
performances => this.performances = performances || [] /* empty array or default value here */
);
}