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

Vasilis Greece
  • 861
  • 1
  • 18
  • 38
  • 1
    Possible duplicate of [Angular2: Cannot read property 'name' of undefined](https://stackoverflow.com/questions/39755336/angular2-cannot-read-property-name-of-undefined) – Igor Mar 01 '19 at 10:37

2 Answers2

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'}
      }
  }
}
Nithya Rajan
  • 4,722
  • 19
  • 30
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() ?

playerone
  • 987
  • 3
  • 22
  • 44