angular - 如何在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>
我想按 FieldDisplayName 排序
解决方案
首先,为什么在接收数据时要遍历数组?您可以使用该.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;
}
});
});
}
推荐阅读
- java - Argon2 php vs Java hash_len
- sql - Oracle SQL 在一列中仅选择 5 位数字行
- api - 如何将我的用户作为成员包含在 Sandbox 中的组类型身份中?
- mysql - 可能 MySQL ibdata1 已损坏
- airflow - 气流:将执行日期范围任务实例标记为成功
- c++ - 如何从 DROPFILES 结构中提取拖放的文件名
- node.js - 是否可以使用 Bunyan 将前端(React)错误记录到后端(Node JS)?
- c++ - 检查是否可以在不丢失信息的情况下将指针存储在 uint64_t
- wordpress - 如何从组/列内部块中排除父块?
- javascript - 如何使用 foreach 循环计算利率?