Johnny
Johnny

Reputation: 291

Angular: How to handle null value in angular material table

I wanted to apply css class based on the status. Eg: if status is Pass, css class .dot .pass should be assigned to span in html. How I can handle the null value if api return status: null. I'm getting this error message ERROR TypeError: Cannot read property 'css' of undefined. I belived this was caused by null value in status.

status.constant.ts

export const STATUSES_KEY = {
  notChecked: 'NOT_CHECKED',
  pass: 'PASS',
  na: 'NA',
  fail: 'FAIL'
};

export const STATUS_STYLING = {
  [STATUSES_KEY.notChecked]: {
    text: 'Not Checked',
    css: 'dot notChecked',
  },
  [STATUSES_KEY.pass]: {
    text: 'Pass',
    css: 'dot pass',
  },
  [STATUSES_KEY.fail]: {
    text: 'Fail',
    css: 'dot fail',
  }
};

app.ts

  generateStatusClass(status: string) {
    if (status) {
      return STATUS_STYLING[status].css;
    } else {
      return;
    }
  }

app.html

<span *ngIf="col === 'status'" class="{{ generateStatusClass(element[col]) }}"></span>

Upvotes: 0

Views: 973

Answers (1)

DaggeJ
DaggeJ

Reputation: 2191

In your generateStatusClass(status: string) method you are checking if status is truthy, but not if there is a value for the status in your dictionary (for example na is not present). Change the code to something like this;

 generateStatusClass(status: string) {
    if (status && STATUS_STYLING[status]) {
      return STATUS_STYLING[status].css;
    } else {
      return;
    }
  }

Also, I am not sure if class={{...}} works. You might want to change this to ngClass, like this;

<span *ngIf="col === 'status'" [ngClass]="generateStatusClass(element[col])"></span>

Upvotes: 1

Related Questions