Joe
Joe

Reputation: 410

Binding to a variable that may not exist

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?

Upvotes: 1

Views: 708

Answers (2)

shrvn
shrvn

Reputation: 93

use below expression in ts file, if myVariable is present its value is displayed else empty will be displayed

 myVariable?myVariable:'';

Upvotes: 0

Barremian
Barremian

Reputation: 31105

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>

Upvotes: 3

Related Questions