Trueser
Trueser

Reputation: 21

angular 2 4 5 - Cannot read property 'name' of undefined angular 5

sorry, English a little

I want : Show in view after back-end server communication. or another solution

view.html

<label> userId : {{ element.userId }} 
<label> brandName : {{ elemnet.brand.name }} ==> ERROR

Cause of error : I think Object initialization issues on the component.ts

component.ts

element: { [k: string]: any } = {}; ==>  Not defined element.brand{}

ngOnint(){
this.getElement()
}

getElement(): void{
this.http.get(getUrl)
     .map(res => {
          this.element = res;

         **element** ==> { 
                      userId : 1,
                      brand {
                             name: 'brandName',
                             id : 1
                            }
                     }
     })
     .catch()
}

Temporary resolution

view.html

<label> userId : {{ element.userId }} 
<label> brandName : {{ elemnet.brand?.name }} ==> Resolve

I want to solve this problem.

Thank you.

have a good day.

Upvotes: 0

Views: 47

Answers (3)

Shrivats
Shrivats

Reputation: 53

Try this

<label *ngIf="element"> userId : {{ element.userId }} </label>

<label *ngIf="element"> brandName : {{ element.brand.name }} </label>

In component.ts file don't initialize element. Leave it like this

public element;

Upvotes: 0

Krishna Rathore
Krishna Rathore

Reputation: 9687

You can try this solution

<label> userId : {{ element?.userId }} 
<label> brandName : {{ elemnet?.brand?.name }}

Upvotes: 0

Carsten
Carsten

Reputation: 4208

Your temporary solution isn't temporary but correct.

Temporary resolution

view.html

<label> userId : {{ element.userId }} 
<label> brandName : {{ elemnet.brand?.name }} ==> Resolve =>> Keep this solution

Upvotes: 2

Related Questions