Search code examples
angularionic3

How to bind an object value to HTML in Angular


I want to print values from a single object in HTML, but it is throwing an error.

{
  "id": "221",
  "user_id": "455",
  "membership_id": "3",
  "is_cemetery": "0",
  "first_name": "tinku",
  "last_name": "tinku",
  "gender": "male",
  "dob": "2019-03-16",
  "i_am": "",
  "looking_for": "",
  "phone": "9876543210",
  "street": "",
  "city": "mohali",
  "state": "",
  "country": "GE",
  "zipcode": "160055",
  "photo": "",
  "description": "test",
  "created_date": "2019-05-27 10:23:46",
  "country_name": "Georgia",
  "image": false,
  "dogs": [{
    "id": "336",
    "user_id": "455",
    "agency_name": "tinkurana99",
    "dog_name": "Tom",
    "training_status": "",
    "selectbreed": "Cross",
    "breed": "261",
    "dog_color": "red",
    "dog_gender": "male",
    "maturity": "Puppy",
    "age_type": "",
    "dog_age": "",
    "age_year": "2",
    "age_month": "2",
    "age_week": "2",
    "eating_habit": "",
    "istrained": "Yes",
    "vaccinated": "yes",
    "description": "Doggy Dating agency",
    "dog_photo": "uploads/5cec705462b13.jpeg",
    "cemetery": "No",
    "start_year": "",
    "end_year": "",
    "cemetery_content": "",
    "iam_status": "4",
    "dog_price": "",
    "status": "active",
    "admin_status": "Approve",
    "created_date": "2019-05-27 10:03:32",
    "breed_name": "Australian Terrier-Akita Inu"
  }]
}

So this object is passed from a TS file:

this.userData = this.response.data;

In the HTML I am accessing the values like this:

{{ userData.city }}

But it is throwing an error that city is undefined. I am using Ionic framework v3 and Angular v5.


Solution

  • Write this:

    {{userData?.city}}
    

    Instead of:

    {{userData.city}}
    

    ? is the safe navigation operator. It checks whether the variable is null or undefined, so that our template won't try to select a property of something falsy.