我是anguar JS的新手,我不知道如何对mat选项中的数据进行排序。请帮助我解决此问题。让我分享我在我身边所做的尝试。
component.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' }
];
}
}
component.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排序
答案 0 :(得分:2)
首先,为什么在接收数据时要遍历数组?您可以使用.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;
}
});
});
}