I receive json data from the backend using a service and I'm displaying it through a loop in main.html. Now there is an array which consists the values of a column that is being displayed. Let's say the array looks like this, colors=[red,blue]. Then I want only the records with red and blue color to be displayed.
main.html
<div class="flip-right" *ngFor="let items of obs | async">
<mat-card>
<mat-card-header>
<mat-card-title>{{items.name}}</mat-card-title>
</mat-card-header>
<mat-card-subtitle>{{items.color}} </mat-card-subtitle>
</mat-card>
</div>
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
main.ts
export class PrivateComponent implements OnInit,OnDestroy {
//filter variables to store the selected values
color=[red,blue];
subscription: Subscription;
@ViewChild(MatPaginator) paginator: MatPaginator;
obs: Observable<any>;
dataSource = new MatTableDataSource();
constructor(
private changeDetectorRef: ChangeDetectorRef,
private cardsInfo :CardsInfoService) {
}
ngOnDestroy(): void {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
if (this.dataSource) {
this.dataSource.disconnect();
}
}
ngOnInit(){
this.cardsInfo.getCardsInfo()
.subscribe(
data => {
this.dataSource.data = data;
});
this.changeDetectorRef.detectChanges();
this.dataSource.paginator = this.paginator;
this.obs = this.dataSource.connect();
}
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
}
}
json data that is being passed through the service
[
{"id":"1","name":"abc","color":"red"},
{"id":"2","name":"def","color":"blue"},
{"id":"3","name":"ghi","color":"green"},
{"id":"4","name":"def","color":"yellow"},
{"id":"5","name":"xyz","color":"red"},
]
Here, I only want the red and blue color to be displayed.
You can use a for-loop on the array1
[array on which you want to check is that color is available or not] and then check for is that color is available in the destination array, so the code will be:
TS code:
import { Component } from '@angular/core';
/**
* @title Basic list
*/
@Component({
selector: 'list-overview-example',
templateUrl: 'list-overview-example.html',
styleUrls: ['list-overview-example.css'],
})
export class ListOverviewExample {
array1: any[] = ['red', 'blue', 'green'];
originalArray = [
{ "id": "1", "name": "abc", "color": "red" },
{ "id": "2", "name": "def", "color": "blue" },
{ "id": "3", "name": "ghi", "color": "green" },
{ "id": "4", "name": "def", "color": "yellow" },
{ "id": "5", "name": "xyz", "color": "red" },
]
filteredArray: any[] = [];
constructor() {
for (var i = 0; i < this.array1.length; i++) {
var list = this.originalArray.filter(x => x.color == this.array1[i]);
list.forEach(x => {
this.filteredArray.push(x);
})
}
console.log(this.filteredArray)
}
}