简体   繁体   English

从 Angular 材料表/JSON 数组中获取最大值

[英]Get max value from Angular Material Table / JSON array

I have created a function to map over a json data to display it as a table using Angular Material.我在 json 数据上创建了 function 到 map,使用 Angular 材料将其显示为表格。 I would like to我想要

  1. Display the highest bidamt and the corresponding from my table in my and在我的表中显示最高的 bidamt 和相应的
  2. Currently my id is arranged in order of timing (ie an earlier entry is displayed as 1, a later entry is displayed as 2 etc.).目前我的id是按时间顺序排列的(即较早的条目显示为1,较晚的条目显示为2等)。 How can I rearrange it to display it in order from highest to lowest bid?我怎样才能重新排列它以从最高到最低出价的顺序显示它?

bid.component.html bid.component.html

<div class="container">
        <div class="highest-amount">
            <span class="highest-amt-text">{{bid.bidamt | max}}</span>
            <span class="highest-amt-name">{{bid.name | max}}</span>
        </div>
        <table mat-table [dataSource]="dataSource" class="mat-elevation-z8" 
        matSort matSortDisableClear matSortActive="bidamt" matSortDirection="desc">
          <ng-container matColumnDef="id">
            <th mat-header-cell *matHeaderCellDef mat-sort-header> No.</th>
            <td mat-cell *matCellDef="let bid"> {{bid.id}} </td>
          </ng-container>
           <ng-container matColumnDef="bidamt">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Bids</th>
            <td mat-cell *matCellDef="let bid"> {{bid.bidamt | number}} UCD</td>
          </ng-container>
          <ng-container matColumnDef="bidname">
            <th mat-header-cell *matHeaderCellDef>Name</th>
            <td mat-cell *matCellDef="let bid"> {{bid.bidname}} </td>
          </ng-container>
          <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
        </table>
        <mat-paginator
          style="color: rgba(255,255,255,0.7)"
          [pageSize]="2"
          [pageSizeOptions]="[2, 5, 10]"
          aria-label="Select page">
        </mat-paginator>
      </div>

bid.json bid.json

{
  "bids": [
    {
      "bidamt": 500,
      "bidname": "Alice",
      "id": 1
    },
    {
      "bidamt": 300,
      "bidname": "Ben",
      "id": 2
    },
    {
      "bidamt": 2000,
      "bidname": "Clare",
      "id": 3
    }
  ]
}

bid.component.ts bid.component.ts

export class BidComponent implements OnInit, OnDestroy, AfterViewInit { 
  displayedColumns: string[] = ['id', 'bidamt', 'name'];
  dataSource!:MatTableDataSource<any>;

  @ViewChild('paginator') paginator! : MatPaginator; 
  @ViewChild(MatSort) matSort! : MatSort;

  subscription: Subscription = new Subscription;

  constructor(private BidService: BidService){ }

  async ngOnInit() {
    this.BidService.getBids().subscribe((response:any) =>{
        this.dataSource = new MatTableDataSource(response);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.matSort;
      })
  }

}

You have two approach:你有两种方法:

  1. Sort the array before create the data source在创建数据源之前对数组进行排序

    this.dataSource = new MatTableDataSource(response.sort((a,b)=>a.bidamt-b.bidamt));
  2. Create a function like创建一个 function 之类的

     sortTable(active:string,direction:string) { this.sort.active=active this.sort.direction=direction as SortDirection this.sort.sortChange.emit( {active: active, direction: direction as SortDirection}); }

    And call after asign the sort并在排序后调用

    ... this.dataSource.sort = this.matSort; this.sortTable('bidamt','asc')

To know the max and store in a variable.知道最大值并存储在变量中。 first declare首先声明

max:number=0

then, simple use reduce of the array in subscribe然后,在订阅中简单使用数组的 reduce

 this.BidService.getBids().subscribe((response:any) =>{
    this.dataSource = new MatTableDataSource(response);
    this.max=response.reduce((a,b)=>b.bidamt>a?b.bidamt:a,-1000)
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.matSort; //<--add this line
  })

Then you can use to add a class in the row然后你可以使用在行中添加一个 class

   <tr mat-row [class.highest-amt-name]="row.bidamt==max" 
        *matRowDef="let row; columns: displayedColumns;"></tr>

or using style-background或使用样式背景

   <tr mat-row [style.background-color]="row.bidamt==max?'red':null" 
        *matRowDef="let row; columns: displayedColumns;"></tr>
   

If you want to use in a span you simply use如果你想在一个跨度中使用,你只需使用

  {{max}}

Update we can add a new property "order" (or reemplace the "id" by order) using simply sort and map, eg更新我们可以使用简单的排序和 map 添加新属性“order”(或按顺序重新放置“id”),例如

response=response.sort((a,b)=>a.bidamt-b.bidamt)
        .map((x:any,i:number)=>({...x,order:i}))
//or
response=response.sort((a,b)=>a.bidamt-b.bidamt)
        .map((x:any,i:number)=>({...x,id:i}))

See how we use the spread operator (the ... x) to create an object with all the properties of the object and a new property "order" or a change of the property "id")看看我们如何使用扩展运算符 (the ... x) 创建一个 object,它具有 object 的所有属性和一个新属性“order”或属性“id”的变化)

update 2 if we want to get the "element" with a "bidamt" greater.如果我们想获得具有更大“bidamt”的“元素”,请更新 2 Using reduce we can do使用 reduce 我们可以做到

this.max=response.reduce((a,b)=>b.bidamt>a.bidamt?b:a,response[0])

Well, if we already have the array sorted is simple好吧,如果我们已经对数组进行了排序就很简单了

    reduce[0] //the first element or 
    reduce[reduce.length-1]  //the last element

in this case max is an object, so to compare the row we need use max.bidmat在这种情况下,max 是 object,因此要比较我们需要使用 max.bidmat 的行

  <tr mat-row [style.background-color]="row.bidamt==max.bidmat?'red':null" 
    *matRowDef="let row; columns: displayedColumns;"></tr>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM