Try to search your question here, if you can't find : Ask Any Question Now ?

How to handle null exception in angular 4

HomeCategory: stackoverflowHow to handle null exception in angular 4
john asked 3 days ago

hey i have some fields in which i am binding my model with html and data coming from backend.
but when i click to edit the data it always say cannot read value of null.
how can i handle this?

here is my 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>

here is the model

export class Patient {
 id?: number;
 Email?: string;
 Address? = {
   Address1: '',
   Address2: '',
   City: '',
   State: '',
   Zip: '',
   County: '',
   Country: ''
   };
 }

ts file

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

 });
}

when i open to edit the address
it throws an error
cannot read property address 1 of null
is there any way to handle this error even if the value coming from is null or empty string?
thanks

1 Answers
Best Answer
Arben answered 3 days ago
Your Answer

18 + 6 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com