Reputation:
I have an array with objects:
let arr = [{type: 1}, {type: 2}, {type: 1}, {type: 1}, {type: 3} {type: 1}];
I need to display this data by group type
:
Type 1
{type: 1}
{type: 1}
{type: 1}
{type: 1}
Type 2
{type: 2}
Type 3
{type: 3}
Is there something in Angular template directives to do that, or anyway I should prepare data and group by type
in component before sending to template?
Upvotes: 0
Views: 1214
Reputation: 26
You can write a function to filter and show what you want in UI or you can use Pipe of Angular to filter it https://angular.io/guide/pipes. Or just simply as the code below:
<ng-container *ngFor="let item of array">
<div *ngIf="item.type === 1">
// show anything by type
</div>
<div *ngIf="item.type === 2">
// show anything by type
</div>
<div *ngIf="item.type === 3">
// show anything by type
</div>
</ng-container>
Upvotes: 0
Reputation: 1780
Create pipe as below.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'typeCheck'})
export class FetchTypePipe implements PipeTransform {
transform(data: any,key:any, type: number): any {
return data.map(obj=>obj[key] == type);
}
}
Upvotes: 0
Reputation: 8767
You should do it in your component (or in pipe, or service). Try to keep the template logic-free.
Upvotes: 1
Reputation: 993
As Zygimantas mentioned, you should do it in your component. A use-case would be:
export class AppComponent implements OnInit {
arrType1: any[];
arrType2: any[];
arr = [{type: 1}, {type: 2}, {type: 1}, {type: 1}, {type: 3} {type: 1}];
constructor() {}
ngOnInit() {
// group them here and assign to arrType1 and arrType2
}
}
Alternatively, you can consider using a Pipe directive if you really want to have it done in your template. Couple your Pipe directive with a ngFor loop.
Upvotes: 1