根据 Angular 中的数组过滤显示的 json 数据 7

Filtering the displayed json data based on an array in Angular 7

我使用服务从后端接收 json 数据,并通过 main.html 中的循环显示它。现在有一个数组,其中包含正在显示的列的值。 假设数组看起来像这样,colors=[red,blue]。然后我只想显示红色和蓝色的记录。

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 正在通过服务传递的数据

[
   {"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"},
  ]

这里我只想显示红色和蓝色

您可以在 array1 [要检查颜色是否可用的数组] 上使用 for 循环,然后检查目标数组中是否有颜色,所以代码将是:

TS代码:

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)
  }
}

Stackblitz