Reputation: 277
I am learning angular ( using angular 5). In the project I have to GET data via HTTP and on click of each element i have to display the details.
I am able to Get the data via HTTP and also able to get details based on clicked element. But I cant show the details, or in other words I dont know how can i show the details.
Here what I have tried.
allEntry = [];
onClickData = [];
getAllData = function() {
this.httpClient.get(this.resourceUrl)
.subscribe(
(data: any[]) => {
this.allEntry = data;
}
)
}
onClick(id: number) {
const myData = this.allEntry .find((element) => element.id === id)
console.log(myData)
this.onClickData = myData;
}
The templete
<div *ngFor ="let el of allEntry ">
<button (click)="onClick(el.id)">{{el.name}}</button>
</div>
<div *ngFor ="let e of onClickData">
{{e.title}}
{{e.age}}
{{e.name}}
</div>
each entry in allEntry contains id,title, name and age. now show i have to display the details on click of a name.
Thanks in advance
Upvotes: 1
Views: 596
Reputation: 13406
ngFor
only works for arrays. onClickData
is an object. To display it properly you should use
<div *ngIf="onClickData">
{{onClickData.title}}
{{onClickData.age}}
{{onClickData.name}}
</div>
Notice the ngIf
. This prevents the div from rendering until onClickData
exists. This will prevent any errors when onClickData
is undefined.
Alternatively you can use the safe navigation opertor
<div>
{{onClickData?.title}}
{{onClickData?.age}}
{{onClickData?.name}}
</div>
Sidenote: You do not need to do the .find()
in your onClick event handler. That handler has access to the entire element. So you can simply pass in the entire object to your method and store it.
// component.html
<div *ngFor ="let el of allEntry ">
<button (click)="onClick(el)">{{el.name}}</button>
</div>
// component.ts
onClick(el){
this.onClickData = el;
}
Upvotes: 2