Вы имеете дело с числами , а не со строками.Вместо этого вы сравниваете строки, поэтому сначала вам нужно привести их к числам:
if (+a1 < +a2) {
//^---- note the + on both a1 and a2.
return 1;
}
if (+a1 > +a2) {
return -1;
}
Обновлен (работает) стек стека:
https://stackblitz.com/edit/angular-hzfjd7?file=src/app/app.component.ts
Другой возможный подход - сначала отобразить элементы и использовать вместо них сопоставленный массив.
protected get numericFruits() {
return this.fruits.map(i => Number(i));
}
Затем используйте numericFruits
вместо fruits
.
Полныйкод:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
isAscendic = true
fruits: any = ["2", "20", "3", "30", "21", ];
send(){
this.isAscendic?this.ascendic():this.descendic()
}
protected get numericFruits() {
return this.fruits.map(i => Number(i));
}
ascendic(){
this.isAscendic = false;
this.fruits = this.numericFruits.sort((a1,a2) => {
if (a1 < a2) {
return 1;
}
if (a1 > a2) {
return -1;
}
return 0;
});
}
descendic(){
this.isAscendic = true
this.fruits = this.numericFruits.sort((a1,a2) => {
if (a1 > a2) {
return 1;
}
if (a1 < a2) {
return -1;
}
return 0;
});
}
}
рабочий стекблиц:
https://stackblitz.com/edit/angular-f5ox91?file=src/app/app.component.ts