0

I am using Angular 5 with Ionic 3. My main problem is that I cannot get the second key object of the object's name "myObj". Below are 2 examples that I have tried so far.

Example 1

home.ts:

...
export class HomePage {
myObj: any ={};

ionViewDidLoad() {
    this.myObj = {
        something: {value: 'value', name: 'name'}
      }
  }
}

home.html:

...
<p>{{myObj.something.name}}</p>

In this case I cannot get name but I can get

<p>{{myObj.something}}</p>

Why is that?

Example 2

home.ts:

...
export class HomePage {
myObj: {something: {value: string, name: string}};

ionViewDidLoad() {
    this.myObj = {
        something: {value: 'value', name: 'name'}
      }
  }
}

home.html:

...
<p>{{myObj.something | json}}</p>

In this example I cannot even get my first level key something.

All above examples shows me in the screen:

cannot read property * of undefined

* depends on property name ex. something or name

1

2 Answers 2

4

Try using ? operator

<p>{{myObj?.something?.name}}</p>

Because you are not initialized the myObj with an empty object. If you initialize it as follows, the ? operator is not needed.

export class HomePage {
myObj: {something: {value: string, name: string}} = { something: {}};

ionViewDidLoad() {
    this.myObj = {
        something: {value: 'value', name: 'name'}
      }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try not to access your object in Template, Can you display values onClick button?

If you want to access in template, initialize variable in constructor not in ionViewDidLoad. Did you try to replace ionViewDidLoad with constuctor() ?

1 Comment

no I didn't but now I found a solution, I will work in both ways now!

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.