28

I'm showing some records coming from an api and some of the results are null and I would like to show a different value in case the response values are null. How would be the best way to do it?

Below is my code:

Component:

import {Component, OnInit} from '@angular/core';
import {PerformancesService} from '../../services/performances.service';
import {Performance} from '../../common/performance';

@Component({
    selector: 'performances',
    templateUrl: './app/components/performances/performances.component.html'
})

export class PerformancesComponent implements OnInit{
    performances: Performance[];

    constructor(private _service : PerformancesService){

    }

    getFunds(){
        this._service.getData().then(
            performances => this.performances = performances
        )
    }

    ngOnInit(){ 
        this.getFunds();
    }
}

template:

<h2>Performance</h2>

<table class="table table-hover">
  <thead>
      <tr>
          <th>Fund Id</th>
          <th>Country Id</th>
          <th>1Mth</th>
          <th>3Mth</th>
          <th>YTD</th>
          <th>1Yr</th>
          <th>3Yrs</th>
          <th>5Yrs</th>
          <th>10Yrs</th>
      </tr>
  </thead>
  <tbody>
      <tr *ngFor="let performance of performances">
        <td>{{performance.id}}</td>
        <td>{{performance.country_id}}</td>
        <td>{{performance.OneMonthBack}}</td>
        <td>{{performance.ThreeMonthsBack}}</td>
        <td>{{performance.YearToDate}}</td>
        <td>{{performance.OneYearBack}}</td>
        <td>{{performance.ThreeYearsBack}}</td>
        <td>{{performance.FiveYearsBack}}</td>
        <td>{{performance.TenYearsBack}}</td>
      </tr>
  </tbody>
</table>

I don't know if I could do it in the template or I should check each value in my component. Any idea? Thanks!

4
  • I have created a method getDefaultIfNull that takes any value as argument and returns actual value if not null and returns "-" if null. Using it like this - {{getDefaultIfNull(performance.OneMonthBack)}} Commented Dec 6, 2016 at 11:08
  • @RehbanKhatri would be it a method or a pipe? Commented Dec 6, 2016 at 11:09
  • A method in component. But you can also create a custom pipe Commented Dec 6, 2016 at 11:12
  • 2
    check <td>{{performance.country_id ? performance.country_id : 2}}</td> Commented Dec 6, 2016 at 11:15

4 Answers 4

30

UPDATED on 03.01.2020

There are multiple ways.

Using only the template:

  1. 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>
  1. check it inline and use a default value:
<tbody>
    <tr *ngFor="let performance of performances">
      <td>{{ performance?.id || 1337 }}</td>
      ...
    </tr>
</tbody>
  1. 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>
  1. 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 */
    );
}
Sign up to request clarification or add additional context in comments.

Comments

30

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 : [])">

4 Comments

This would check if the array itself is null, but I'm pretty sure they want to check individual elements within the array.
@JohnMontgomery should I delete this answer? I don't know the protocol for this.
great answer. some of us were actually looking for this. thanks.
Brilliant!!! If iterating over object with array property do: <tr *ngFor="let performance of (obj?.performances ? obj?.performances : [])">
-1

The simplest way - use initialization:

  projects: ProjectData[] = [];
  services: ServiceData[] = [];
  members: MemberData[] = [];

This will make *ngFor iterate zero times.

Comments

-2

Use safe navigation operator(?) along with || operator. Lesser code than all above solutions.

<tbody>
    <tr *ngFor="let performance of performances">
      <td>{{performance?.id || : 1234}}</td>
      ...
    </tr>
</tbody>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.