2

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
  • 1,940
  • 4
  • 22
  • 55

2 Answers2

5

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
  • 65,481
  • 11
  • 106
  • 136
1

How about plain old ?: ternary operator :

this.recordClosedDate = this.flower.recordClosedDate !=null ?  this.flower.recordClosedDate : "--"
stackFan
  • 1,368
  • 13
  • 20