Search code examples
angularionic-frameworkionic4

Dealing with null-able objects in ion-input


I'm trying to generate an editable table based on the result of an API I'm calling, which can look like this(json below). The reason why some data are null is because I'm calling a text recognition API so it will only show what has been detected from an image.

Json result:

{
    "restaurant": null,
    "details": [
        {
            "text": null,
            "price": {
                "unitPrice": 5.0,
                "coordinateX": 389
            }
        },
        {
            "text": {
                "text": "Americano",
                "coordinateX": 311
            },
            "price": null
        },
        {
            "text": {
                "text": "Latte",
                "coordinateX": 130
            },
            "price": {
                "unitPrice": 43.24,
                "coordinateX": 205,
            }
        }
    ]
} 

Upon getting the result from the API, I then map it to an object ImageResult:

Object:

export class ImageResult {
    constructor(
        public Restaurant: string,
        public CapturedDetails: Details[]
    ) {}
  }

Call:

this.textCaptureService.GetText(formData).subscribe(data => {
        this.result = data;
      });

My issue is that I'm getting an error of cannot read property ___ of null when parts of the object are null in the ion-input tags. How do I deal with Objects that can have null properties. E.g. if null, then display blank or empty string

<ion-input [disabled]="false" [(ngModel)]="result.Restaurant" autofocus="true"> </ion-input>
<ion-row *ngFor="let item of items.Details">
      <ion-col></ion-col>
      <ion-col size="3" class="prices-table-name">
        <ion-input [disabled]="!true" [(ngModel)]="result.Text.Text" (press)="setEditable(item.Text.Text)"> </ion-input>
      </ion-col>
      <ion-col size="3" class="prices-table-value">
        <ion-input [disabled]="!true" [(ngModel)]="result.Price.UnitPrice" (press)="setEditable(item.Price.UnitPrice)"> </ion-input>
      </ion-col>
      <ion-col></ion-col>
    </ion-row>

Solution

  • Use *ngIf to check whether result is null or not.

    <ion-input *ngIf="result !== null" [disabled]="false" [(ngModel)]="result.Restaurant" autofocus="true"> </ion-input>