绑定到一个可能不存在的变量

Binding to a variable that may not exist

myVariable 可能不存在时,绑定到 myVariable 的正确方法是什么? (myVariable 来自可能不是 运行 的服务)

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

将输入组件包装在 div 中,例如:<div *ngIf="myVariable"></div> 将起作用(停止运行时错误),但该组件将丢失。有没有一种优雅的方式我仍然可以显示组件,没有错误,无论 myVariable 是否存在?

解决方案 1:使用 ||

一种方法是使用 || 在第一个值未定义时使用备用值。

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

如果 myVariable 未定义,则使用字符串 Default

解决方案 2:使用 *ngIfelse

另一个基本的解决方案是通过利用 *ngIfelse 块来拥有两个版本的 input 标签。一种有 myVariable,一种没有。

<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>

在 ts 文件中使用下面的表达式,如果 myVariable 存在则显示其值,否则显示空值

 myVariable?myVariable:'';