You can achieve it by following below codes.
First of all create a custom pipe as shown below
import { Pipe } from '@angular/core';
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(value: Array<any>, field: string): Array<any> {
const groupedObj = value.reduce((prev, cur)=> {
if(!prev[cur[field]]) {
prev[cur[field]] = [cur];
} else {
prev[cur[field]].push(cur);
}
return prev;
}, {});
return Object.keys(groupedObj).map(key => return { key, value: groupedObj[key] });
}
}
Then add the following in your component where you have to inject the custom pipe previously created.
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Menu</h2>
<div *ngFor="let menu of menuList | groupBy:'txt' ">
<span style="font-weight: bold;">{{ menu.key }} </span>
<div *ngFor="let val of menu.value">{{ val }}</div>
</div>
</div>
`,
pipes: [GroupByPipe],
directives: []
})
I have slightly modified the JSON array to support the format you mentioned in the question
this.menuList=[ {txt:'Briyani',item:"chicken briyani"},
{txt:'Indian rice',item:"veg"},
{txt:'Rice & noodles',item:"veg"},
{txt:'grill & shawarma',item:"fish"},
{txt:'tandoori',item:"chicken"},
{txt:'starter',item:"chicken"},
{txt:'dishes',item:"egg"},
{txt:'Briyani',item:"mutton briyani"},
{txt:'Briyani',item:"fish briyani"}];
if you have JSON like this
this.menuList=[{
"txt": "Briyani",
"item": [{
"type": "Chicken Briyani",
"price": "180",
"img": "assets/images/3.JPG"
}, {
"type": "Mutton Briyani",
"price": "180",
"img": "assets/images/3.JPG"
}, {
"type": "Prawn Briyani",
"price": "180",
"img": "assets/images/3.JPG"
}]
}, {
"txt": "Indian Rice",
"item": [{
"type": "Chicken Rice",
"price": "180",
"img": "assets/images/3.JPG"
}, {
"type": "Fish Rice",
"price": "180",
"img": "assets/images/3.JPG"
}]
}];
then you can follow the code below to achieve your task.
<div *ngFor="let menu of menuList">
<h5>{{menu.txt}}</h5>
<div *ngFor="let it of menu.item">
<span>{{it.type}}</span>
<span>{{it.price}}</span>
</div>
</div>
Plunker Example
I hope this will fix your problem. If any suggestions or doubts let me know. Thanks.