Javascript 如何处理角度4中的空异常
嘿,我有一些字段,在这些字段中我用html和来自后端的数据绑定我的模型。 但当我点击编辑数据时,它总是说不能读取null值。 我该怎么办 这是我的htmlJavascript 如何处理角度4中的空异常,javascript,angular,typescript,data-binding,Javascript,Angular,Typescript,Data Binding,嘿,我有一些字段,在这些字段中我用html和来自后端的数据绑定我的模型。 但当我点击编辑数据时,它总是说不能读取null值。 我该怎么办 这是我的html <div class="form-group"> <input type="text" [(ngModel)]="patient?.Address.Address1" name="address1" class="form-control input-underline input-
<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};
}
});
});
}
当我打开以编辑地址时
它抛出了一个错误
无法读取null的属性地址1
即使来自的值为null或空字符串,是否有方法处理此错误?
谢谢您正在尝试对可能不存在的对象使用双向绑定,而该对象也可能具有可能不存在的属性。这在使用[(ngModel)]时不起作用,但如果像这样拆分绑定,则可以起作用
<input type="text" [ngModel]="patient?.Address?.Address1" (ngModelChange)="functionToHandleSettingValue($event)" name="address1" >
患者和地址上都有elvis运算符,因为两者都可以为空。您不能执行[(ngModel)]=“patient?.Address.Address1 | null”之类的操作吗?听起来不太复杂,您可以在不返回任何内容时设置为默认值,或者只处理空/未定义/空字符串。我知道这听起来很简单,我也会这么做,但似乎无法处理它。这是唯一一个失败的字段,还是因为该字段是第一个绑定而失败?不,每个地址值都失败
[ngModel]="patient?.Address?.Address1"