[英]Angular Sort by button click
Hey so i'm a beginner trying to understand angularjs/typescript. 嗨,所以我是一个初学者,试图了解angularjs / typescript。
I've got an array of fruits written in an unordered list in which i want to sort by descending order and reverse search it in alphabetic order via a button. 我在无序列表中写了一系列水果,我要按降序排序并通过按钮按字母顺序反向搜索。 However I don't know what the function should like... Any help is appriciated 但是我不知道该功能应该是什么...寻求任何帮助
Html: HTML:
export class AppComponent {
fruits: string[] = ["Apple", "Banana", "Orange", "Peach", "Pear", ];
}
<ul>
<li *ngFor="let fruits of fruits">{{fruits}}
</li>
</ul>
<button ng-click="send()">Sort </button>
Ok fruits where is? 好水果在哪里?
Anyway: 无论如何:
export class AppComponent {
cities: string[] = [ "Pear","Banana", "Apple", "Orange", "Peach" ];
}
Ok, now 现在可以
<ul>
<li *ngFor="let city of cities">{{city}}
</li>
</ul>
<button (click)="send()">Sort </button>
And use the function: 并使用功能:
send(){
this.cities = this.cities.sort();
}
you can use sort() function. 您可以使用sort()函数。
send(){
this.fruits = this.fruits.sort((n1,n2) => {
if (n1 < n2) {
return 1;
}
if (n1 > n2) {
return -1;
}
return 0;
});
}
This is the link to your solution. 这是您的解决方案的链接。 stackBlitz stackBlitz
change the sort()
so that it sorts string. 更改sort()
以便对字符串进行排序。
send(){
this.fruits.sort((n1,n2) => {
return n1.localeCompare(n2)
});
take a look at the stackblitz example, stackblitz link 看一下stackblitz示例, stackblitz链接
To toggle, set a variable, check the variable and return the value. 要进行切换,请设置一个变量,检查该变量并返回值。
send(){
this.order = !this.order;
this.fruits.sort((n1,n2) => {
return (this.order)? n1.localeCompare(n2):n2.localeCompare(n1);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.