javascript - 如何处理角度4中的空异常
问题描述
嘿,我有一些字段,我在其中将我的模型与来自后端的 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};
}
});
});
}
当我打开编辑地址时,它抛出一个错误 无法读取 null 的属性地址 1 是否有任何方法可以处理此错误,即使来自的值为 null 或空字符串?谢谢
解决方案
您正在做的是尝试对可能不存在的对象使用 2 方式绑定,该对象也具有可能不存在的属性。这在使用 [(ngModel)] 时不起作用,但如果您像这样拆分绑定,则可以工作。
<input type="text" [ngModel]="patient?.Address?.Address1" (ngModelChange)="functionToHandleSettingValue($event)" name="address1" >
通过这种方式,您正在处理数据与 ngModel 的绑定以及数据与 ngModelChange 的绑定。
另请注意,在 ngModel 中,该语句应为
[ngModel]="patient?.Address?.Address1"
对病人和地址都有一个 elvis 运算符,因为两者都是可以为空的。
推荐阅读
- c++ - 矢量指针和检索数据
- apache - Apache 在步骤 NAMESPACE 失败
- amazon-web-services - aws ec2:最近我通过了高比率 1/2 检查,我怎样才能发现我的实例有什么问题?
- java - 如何实例化 java.security.Principal?所有子类都已弃用
- jquery - 使用 .is() 检查多个 ID
- javascript - Math.random() 函数实际上是分形吗?
- python - 优化时间序列的日期函数
- python-3.x - 模拟 session.add 并返回由数据库表生成的主键
- tkinter - 如何使 Checkbutton 的变量工作并在屏幕上显示一些按钮?
- html - 我有一个问题,当 .css 文件位于另一个文件夹中时,我的 css 无法在浏览器中工作,但它在 Windows pc 中的工作方式相同