首页 > 解决方案 > 如何处理空值?

问题描述

我想创建一个可用于编辑现有项目或创建新项目的表单。在创建一个新的情况下,一个空对象被传递给一个表单并且应该被正确处理以防止错误。

形式定义如下:

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

如果数据不为空,则按预期填充表单。但是,如果数据为空,则占位符为空白,而不是显示占位符文本。有谁知道处理空值的好方法是什么?

标签: angularangular-material

解决方案


推荐阅读