Reputation: 2157
I am trying out angular, I have a home component that displays a list of countries, I want to display more information about the country in a detail view.
I can actually see the data when I pipe it to json in the template but can't access properties of the object.
in the home.html I have
<ion-list>
<ion-item *ngFor="let country of countries">
<ion-avatar item-start>
<img [src]="country.flag" />
</ion-avatar>
<h5>{{country.name}}</h5>
<p>{{country.exchange_count}} Exchanges</p>
<button ion-button primary outline item-end (click)="about(country)">View</button>
</ion-item>
</ion-list>
home.ts
about(country){
console.log(typeof(country))
this.navCtrl.push(AboutPage, {country:country})
}
about.ts, the country's name is printed on the console
ionViewDidLoad () {
this.country = this.navParams.get('country');
console.log(this.country.name);
}
about.hmtl, here is where doing something like country.name
raised an error can't access property name of undefined
but when I do as below, the dumped data shows on the page.
<ion-content>
{{country | json}}
<!-- {{country.name}} -->
</ion-content>
on the about.html page, here is the result when piped into json, I trimmed the data for brevity
{"id":"1","name":"Ghana","iso_code":"GHS","currency":"GHS",
"exchange_count":1}
I have tried several things, what am I missing?
Upvotes: 5
Views: 13489
Reputation: 1176
I had the same issue. I had an object(home) that has two properties id and name When I tried to access them in the HTML, the console logged me following error
ERROR TypeError: Cannot read properties of undefined (reading 'id')
So I had to add *ngIf element to verify the object is present.
<table class="table" *ngIf="homeToDelete">
<thead>
<tr>
<th class="left">{{labels.id}}</th>
<th>{{labels.name}}</th>
</tr>
</thead>
<tbody>
<tr>
<td class="left">{{homeToDelete.id}}</td>
<td>{{homeToDelete.name}}</td>
</tr>
</tbody>
</table>
Upvotes: 0
Reputation: 222582
Try to use safe navigation operator or ngif to verify the object is present , or you can initialize the country object as well.
<ion-content>
{{country?.name}}
</ion-content>
or
constructor() { public const country = {name:'',... etc}};
Upvotes: 7