"Cannot read property 'name' of undefined" before fetching data from the server

651 views angular
3

I have my html

<input name="name" [(ngModel)]="address.name" matInput >

and my ts like so

  public address: Address;

  ...

  ngOnInit() {
    this.service.getAddress(1).subscribe(address => {          
      this.address = address;
    });
  }

and my interface looks like

export interface Address {
  ...
  name: string;
}

When I'm trying to populate the input I get the error:

TypeError: Cannot read property 'name' of undefined

I know this happens because the address object is null until it gets populated in the subscribe method. How can I get rid of this error?

answered question

You could use *ngIf to create the element when address exists

2 Answers

10

Initialize to empty Object as follows,

public address: Address = {}; //make sure to use your type within the constructor

or use *ngIf in the template,

<input name="name" *ngIf="address" [(ngModel)]="address.name" matInput >

posted this
11

Use *ngIf to create the element when an address exists:

<input *ngIf="address" name="name" [(ngModel)]="address.name" matInput>

posted this

Have an answer?

JD

Please login first before posting an answer.