undefined error while accessing an object from .ts

2019-08-19 04:10发布

I am trying to access an object value sent via a .ts file on .html file but it shows

"Error: Uncaught (in promise): TypeError: co.productdetail is undefined
View."

here the productdetail is the variable name that i am trying to pass from the .ts file to the .html file.This is the way I am trying to print the name attribute of object in the html file <h3>{{productdetail.name}}</h3>. however following seems to work fine in another file.

<div class="width50" *ngFor="let object of dataList">
<img src="{{object.images[0].src}}" width="150"  (click)="navigateToPage(object.id)" />

here datalist is an array of objects passed from the .ts file to .html file. Kindly suggest a solution to the same.

1条回答
beautiful°
2楼-- · 2019-08-19 04:48

Use typesafe ? operator to avoid this error

<h3>{{productdetail?.name}}</h3>

Reason:

  • DOM elements are rendered even before ngOnInit() is fired.
  • If you are using data from the service response, the bindings will have them as undefined until the response is received.
查看更多
登录 后发表回答