【发布时间】:2019-09-06 20:08:34
【问题描述】:
嘿,我有一些字段,我在其中将我的模型与来自后端的 html 和数据绑定。 但是当我单击编辑数据时,它总是说无法读取空值。 我该如何处理?
这是我的 html
<div class="form-group">
<input type="text" [(ngModel)]="patient?.Address.Address1" name="address1"
class="form-control input-underline input-lg" id="address1"
placeholder="Address1" maxlength="50" autocomplete="off">
</div>
<div class="form-group">
<input type="text" [(ngModel)]="patient?.Address.Address2" name="address2"
class="form-control input-underline input-lg" id="address2"
placeholder="Address 2" maxlength="50" autocomplete="off">
</div>
<div class="form-group">
<div class="row">
<div class="col-6">
<input type="text" [(ngModel)]="patient?.Address.City" name="city"
class="form-control input-underline input-lg" id="city" inputName
placeholder="City" [required]="isOfficeStaff">
</div>
<div class="col-3">
<select [(ngModel)]="patient?.Address.State" name="state"
[ngClass]="{'text-dimmed': !patient?.Address.State}"
class="form-control input-underline input-lg">
<option [ngValue]="null" disabled>State</option>
<option *ngFor="let state of states" [value]="state.abbreviation">
{{state.abbreviation}}
</option>
</select>
</div>
<div class="col-3">
<input type="text" [(ngModel)]="patient?.Address.Zip" name="zip"
class="form-control input-underline input-lg" id="zipcode" maxlength="5"
pattern="\d{5}" placeholder="Zipcode" [required]="isOfficeStaff">
</div>
</div>
</div>
这是模型
export class Patient {
id?: number;
Email?: string;
Address? = {
Address1: '',
Address2: '',
City: '',
State: '',
Zip: '',
County: '',
Country: ''
};
}
ts 文件
public patient: Patient;
ngOnInit() {
this.store.select("patient").subscribe(patient => {
this.patient = Object.assign({}, new Patient(), patient);
if (this.patient.Id && !this.patientSnapshot) {
this.patientSnapshot = {...this.patient};
}
});
});
}
当我打开编辑地址时 它抛出一个错误 无法读取属性地址 1 of null 即使来自的值为空或空字符串,是否有任何方法可以处理此错误? 谢谢
【问题讨论】:
-
你不能做一个 [(ngModel)]="patient?.Address.Address1 | null" 或类似的东西吗?对我来说听起来并不太复杂,您要么在没有返回任何内容时设置为默认值,要么只处理空/未定义/空字符串。
-
我知道这听起来很容易,我也会这样做,但似乎无法处理。
-
这是唯一失败的字段,还是因为该字段是第一个绑定而仅在该字段失败?
-
不,每个地址值都失败
标签: javascript angular typescript data-binding