2

In angular 6 while I am binding a nested model to view, its giving error as "Can't read property of undefined".

Model-

    export class Country {
    CountryID: number;
    CountryCode: string;
    CountryName: string;
    CurrencyCode: string;
}

export class Data {
    Country: Country[]
}

export class CountryMaster {
    IsSuccess: boolean;
    ErrorCode: string;
    ErrorDescription: string;
    Data: Data;
}

Component

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CountryMaster, Country,Data } from '../Shared/Model/CountryModel';

@Component({
  selector: 'app-shopping',
  templateUrl: './shopping.component.html',
  styleUrls: ['./shopping.component.css']
})
export class ShoppingComponent implements OnInit {

  constructor(public httpCl: HttpClient) { }
  ListOfCountry: Data;
  countries: Country[];

  ngOnInit() {
    this.BindCountry();
  }

  BindCountry(): void {


  this.httpCl.get("http://localhost:59049/api/Country/GetCountry").subscribe(
      (successData: CountryMaster) => {
        this.ListOfCountry = successData.Data;
      },failData => {
        //alert(failData);        
      });
  }
}

and template

  <div *ngFor="let ctry of ListOfCountry.Country">
  <div>
    <label>{{ctry.CountryCode}}</label>
    <label>{{ctry.CountryName}}</label>
  </div>
</div>

Though it bind the data but also give the error in console. When i pass the list of Country model to view then it works fine or when i added a condition *ngIf="ListOfCountry" then there is no error. Can anyone help me why its happening when I am binding with nested object

error

2 Answers 2

1

This may happen in cases where your data response is received after the view has been rendered.

Though the API has been called in ngOnInit() but depending upon your API response time, data may arrive after view rendering.

In that case, the ListOfCountry: Data; doesn't have the definition for the Data object type. It is just declared, not defined. Thus, it isn't able to find the Country object in it.

You may declare your object as below to ignore this condition:

ListOfCountry: Data = { Country = [] };
Sign up to request clarification or add additional context in comments.

Comments

1

Try by using a safe navigation operator ?

div *ngFor="let ctry of ListOfCountry?.Country">
  <div>
    <label>{{ctry?.CountryCode}}</label>
    <label>{{ctry?.CountryName}}</label>
  </div>
</div>

1 Comment

Its same as adding <div *ngIf="ListOfCountry"> before binding, which will solve the issue but main concern is why it's happening.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.