首页 > 解决方案 > 如何处理角度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 或空字符串?谢谢

标签: javascriptangulartypescriptdata-binding

解决方案


您正在做的是尝试对可能不存在的对象使用 2 方式绑定,该对象也具有可能不存在的属性。这在使用 [(ngModel)] 时不起作用,但如果您像这样拆分绑定,则可以工作。

<input type="text" [ngModel]="patient?.Address?.Address1" (ngModelChange)="functionToHandleSettingValue($event)" name="address1" >

通过这种方式,您正在处理数据与 ngModel 的绑定以及数据与 ngModelChange 的绑定。

另请注意,在 ngModel 中,该语句应为

[ngModel]="patient?.Address?.Address1"

对病人和地址都有一个 elvis 运算符,因为两者都是可以为空的。


推荐阅读