首页 > 解决方案 > 如何在angualr JS中对mat选项进行排序?

问题描述

我是 anguar JS 的新手,我不知道如何在 mat 选项中对数据进行排序。请帮我解决这个问题。让我分享我从我身边尝试过的东西。

组件.ts

using service i am calling API and data is array format.
ngOnInit() {
    this.woService.GetFilters().subscribe((r: any) => {
      for (let index = 0; index < r.length; index++) {
        this.fields = r;
      }
    });
  }

onChange1(e) {
    this.fieldText1 = e.source.selected.viewValue;
    for (let index = 0; index < this.fields.length; index++) {
      if (e.value === this.fields[index].FieldName) {
        this.fieldType1 = this.fields[index].FieldDataType;
      }
    }
    if (this.fieldType1 === 'integer') {
      this.operations1 = [
        { value: 'EQ', viewValue: 'equal to' },
        { value: 'GT', viewValue: 'greater than' },
        { value: 'LT', viewValue: 'less than' },
        { value: 'GE', viewValue: 'greater than or equals' },
        { value: 'LE', viewValue: 'less than or equals' }
      ];
    } else if (this.fieldType1 === 'character') {
      this.operations1 = [
        { value: 'BEGINS', viewValue: 'begins with' },
        { value: 'MATCHES', viewValue: 'matches' },
        { value: 'EQ', viewValue: 'equal to' }
      ];
    } else if (this.fieldType1 === 'date') {
      this.operations1 = [
        { value: 'EQ', viewValue: 'equal to' },
        { value: 'GT', viewValue: 'greater than' },
        { value: 'LT', viewValue: 'less than' },
        { value: 'GE', viewValue: 'greater than or equals' },
        { value: 'LE', viewValue: 'less than or equals' }
      ];
    } else if (this.fieldType1 === 'logical') {
      this.operations1 = [
        { value: 'EQ', viewValue: 'equal to' }
      ];
    } else if (this.fieldType1 === 'decimal') {
      this.operations1 = [
        { value: 'EQ', viewValue: 'equal to' }
      ];
    }
  }

组件.html

 <mat-form-field appearance="outline" style="width: 33%;">
                    <mat-label">Field</mat-label>
                    <mat-select (selectionChange)="onChange1($event)" formControlName="field1">
                        <mat-option *ngFor="let field of fields" [value]="field.FieldName ">
                            {{field.FieldDisplayName}}
                        </mat-option>
                    </mat-select>
 </mat-form-field>

来自 API 的 JSON 格式 在此处输入图像描述

我想按 FieldDisplayName 排序

标签: angularkendo-uiangular-material

解决方案


首先,为什么在接收数据时要遍历数组?您可以使用该.sort()功能轻松对数组进行排序。

ngOnInit() {
  this.woService.GetFilters().subscribe((r: any[]) => {
    this.fields = [];
    r.forEach((data: any) => {
      if(!this.fields.find((field) => field.FieldDisplayName == data.FieldDisplayName) {
        this.fields.push(data);
      }
    });
    this.fields.sort((a, b) => {
       if(a.FieldDisplayName > b.FieldDisplayName) {
         return 1;
       } else if(a.FieldDisplayName < b.FieldDisplayName)
         return -1;
       } else {
         return 0;
       }
    });
  });
}

推荐阅读