angular - 如何处理空值?
问题描述
我想创建一个可用于编辑现有项目或创建新项目的表单。在创建一个新的情况下,一个空对象被传递给一个表单并且应该被正确处理以防止错误。
形式定义如下:
<section>
<form fxLayout="column" fxLayoutAlign="center center" #f="ngForm" (ngSubmit)=onSubmit(f)>
<mat-form-field>
<input type="text" matInput placeholder="Label" ngModel name="label" [ngModel]="data?.label" required>
</mat-form-field>
<mat-form-field>
<input type="text" matInput placeholder="Licence Plate" ngModel name="licencePlate" [ngModel]="data?.licencePlate">
</mat-form-field>
<mat-form-field>
<input type="text" matInput placeholder="Capacity (kg)" ngModel name="capacityKg" [ngModel]="data?.capacityKg">
</mat-form-field>
<mat-form-field>
<input type="text" matInput placeholder="Capacity (pallets)" ngModel name="capacityPellets" [ngModel]="data?.capacityPellets" required>
</mat-form-field>
<div fxFlex fxLayout="row" id='btns' fxLayoutAlign="right">
<button type="submit" mat-raised-button color="primary">Cancel</button>
<button type="submit" mat-raised-button color="primary" [disabled]="f.invalid">Save</button>
</div>
</form>
</section>
构造函数和接口定义如下:
constructor(
public dialogRef: MatDialogRef<VehicleComponent>,
@Inject(MAT_DIALOG_DATA) public data: VehicleData) {}
}
export interface VehicleData {
position: number;
label: string;
licencePlate: string;
capacityKg: number;
capacityPellets: number;
}
如果数据不为空,则按预期填充表单。但是,如果数据为空,则占位符为空白,而不是显示占位符文本。有谁知道处理空值的好方法是什么?
解决方案
推荐阅读
- google-sheets - 数据工作室过滤器 - 一些字符串数据自动转换为日期范围
- debugging - 使用单 GPU 和 Visual Studio 进行 Cuda 调试
- javascript - 如何在打开随机播放的情况下跳到下一首歌曲?反应原生
- c++ - 具有模板参数的返回类型的 C++ lambda 函数的 CC 模式缩进
- redux - 需要帮助在 Redux 开发工具中显示和查看状态
- ios - 访问 ARKit – iOS App 拒绝指南 2.5.1
- bash - 如何生成没有某些字符或允许某些字符集的openssl河豚
- reactjs - 当我将学生传递给 redux 中的操作时,我的图像数组为空,但它在邮递员中工作
- mysql - 如何获取表格中每个类别的最新日期?
- php - 我可以将 WebSocket 从 ws 更改为 wss 吗?(000webhost)