0

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>

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

6 Comments

error has gone now but css class not applying in span class. Eventhough I used [ngClass]
@Johnny - you might want to console.log(status) in your method to see that you're getting the expected value from element[col].
Yes, it is returning correct value but not reflecting in class
Do you see the class applied when inspecting the element? The css class might be out of scope if you're sure the correct string really gets returned from your method.
Yes it is. But when inspect the element, it doesn't reflect. Weird
|

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.