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



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

主.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>

主目录

   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

最新更新