3

I am sending data to Angular but one of the value (closed date) for a record is null. How can I handle this in Angular so that if value is null , it changed to --

  getDetails() {
    this.myService.getFlowerDetails(this.flowerId, this.flowerName).subscribe(
      res => {
        this.flower = res;
        if(this.flower !== undefined){
          this.flowerName = this.flower.flowerName;
          this.flowerId = this.flower.flowerId.toString();
          this.flowerCategory = this.flower.flowerCategory;
          this.recordCreateDate = this.flower.recordCreateDate.toString();
          this.recordClosedDate = this.flower.recordClosedDate.toString(); // this is null in the backend
        }
        else{
          this.flowerName = "--";
          this.flowerId = "--";
          this.flowerCategory = "--";
          this.recordCreateDate = "--";
          this.recordClosedDate = "--";
        }
      }, er => {
    this.throwError = er;
});

I get the following error. This is not the entire stack trace (not sure if its needed)

TypeError
​
columnNumber: 17
​
fileName: "http://localhost:4200/main.bundle.js"
​
lineNumber: 1738
​
message: "_this.flower.recordClosedDate is null"
Maddy
  • 2,025
  • 5
  • 26
  • 59

2 Answers2

6

The || operator can be used to set a default value, in cases where this.flower.recordClosedDate is falsy (undefined, null, empty string, zero):

this.recordClosedDate = (this.flower.recordClosedDate || "--").toString();
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
1

How about plain old ?: ternary operator :

this.recordClosedDate = this.flower.recordClosedDate !=null ?  this.flower.recordClosedDate : "--"
stackFan
  • 1,528
  • 15
  • 22