Reputation: 27
I have this array and would like to categorize the name
value, based on the group
value in my HTML file.
This is a snippet of relevant parts from my .TS file where I have the arrays.
export let Students = [
{
'name': 'Alex',
'age': '14',
'group': 'Regular',
},
I have tried to remove the tags, but that does not give the desired result. I feel like that there is a much more efficient and simple way of going about this.
Upvotes: 1
Views: 65
Reputation: 8670
You could group your first array by group, and then iterate over both array. :
//so we can access "this" in the callback.
let parent = this;
this.Students.forEach((item) => {
if(!parent.groupedStudents.hasOwnProperty(item.group)) {
parent.groupedStudents[item.group] = { title: item.group, students: []}
}
parent.groupedStudents[item.group].students.push(item);
});
// we cannot iterate over object in ngFor, so we use only the values.
this.groupedStudents = Object.values(this.groupedStudents);
And in your template
<ng-container *ngFor="let item of main.groupedStudents">
<ion-list-header>
<ion-label>{{item.title}}</ion-label>
</ion-list-header>
<ion-label *ngFor="let student of item.students>{{student.name}}</ion-label>
</ng-container>
I have made a basic angular app using this here
Upvotes: 2