Mateut Alin
Mateut Alin

Reputation: 1295

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

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?

Upvotes: 1

Views: 185

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222720

Initialize to empty Object as follows,

public address = new Address();

or use *ngIf in the template (dirty),

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

and is export class Address {...}

Upvotes: 1

SiddAjmera
SiddAjmera

Reputation: 39482

If you want to consider this, try using any as an optional type and then assign {} to address:

public address: (Address | any) = {};

Upvotes: 1

Related Questions