[Fixed] Binding to a variable that may not exist

Issue

What is the correct way of binding to myVariable when myVariable may not exist? (myVariable is from a service that may not be running)

<input pInputText type="text" [size]="size" [value]="myVariable" style="cursor: pointer;">

Wrapping the input component in a div, eg: <div *ngIf="myVariable"></div> will work (stop runtime errors) but the component would then be missing. Is there an elegant way I can still display the component, without errors, whether myVariable exists or not?

Solution

Solution 1: Using ||

One way would be to use || to use an alternate value when the first value is undefined.

<input pInputText type="text" [size]="size" [value]="myVariable || 'Default'" style="cursor: pointer;">

Here if the myVariable is undefined, string Default would be used.

Solution 2: using *ngIf‘s else

Another rudimentary solution would be to have two versions of input tag by leveraging *ngIf‘s else block. One with myVariable and one without.

<ng-container *ngIf="myVariable; else noVariable">
  <input pInputText type="text" [size]="size" [value]="myVariable" style="cursor: pointer;">
</ng-container>
<ng-template #noVariable>
  <input pInputText type="text" [size]="size" style="cursor: pointer;">
</ng-template>

Leave a Reply

(*) Required, Your email will not be published