Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 按角度排序2_Angular_Typescript - Fatal编程技术网

Angular 按角度排序2

Angular 按角度排序2,angular,typescript,Angular,Typescript,我如何重写这段代码,使它不仅可以从A-Z排序,而且可以使用一个按钮进行排序。这是我的代码,但它不能正常工作。它只从A-Z排序,而在相反的方向不需要 sortType(sort: string, order: string){ if(sort === 'name') { this.projects = this.projects.sort(this.sortByCountryName) console.log(this.sprBitTypes);

我如何重写这段代码,使它不仅可以从A-Z排序,而且可以使用一个按钮进行排序。这是我的代码,但它不能正常工作。它只从A-Z排序,而在相反的方向不需要

sortType(sort: string, order: string){
    if(sort === 'name') {
        this.projects = this.projects.sort(this.sortByCountryName)
            console.log(this.sprBitTypes);
    } 
    else {this.projects = this.projects.sort(this.sortByCountryName1);}

}


sortByCountryName(c1: SprBitType, c2:SprBitType){
    if(c1.name > c2.name)  return 1
        else if (c1.name == c2.name)return 0
    else return -1  
}
sortByCountryName1(c1: SprBitType, c2:SprBitType){
    if(c1.name < c2.name)  return 1
        else if (c1.name == c2.name)return 0
    else return -1  
}`enter code here`
sortType(排序:字符串,顺序:字符串){
如果(排序=='name'){
this.projects=this.projects.sort(this.sortByCountryName)
console.log(this.sprBitTypes);
} 
else{this.projects=this.projects.sort(this.sortByCountryName1);}
}
sortByCountryName(c1:SprBitType,c2:SprBitType){
如果(c1.name>c2.name)返回1
else if(c1.name==c2.name)返回0
否则返回-1
}
sortByCountryName1(c1:SprBitType,c2:SprBitType){
if(c1.name
html:

名称
使用
sort((c1:SprBitType,c2:SprBitType)=>c1.name-c2.name)
用于升序和

sort((c1:SprBitType,c2:SprBitType)=>c2.name-c1.name)
用于降序

sortType(sort: string, order: string) {
    if (sort === 'name') {
        this.projects = this.projects.sort((c1: SprBitType, c2:SprBitType) => c1.name - c2.name)
        console.log(this.sprBitTypes);
    } else {
        this.projects = this.projects.sort((c1: SprBitType, c2:SprBitType) => c2.name - c1.name)
    }

}

为了避免不必要的代码重复,我建议第二类调用第一类
sortByCountryName1(c1,c2){this.sortByCountryName(c2,c1);}
。你也可以在结尾用“reverse”而不是“1”来重命名它。只是提醒一下Angular使用TypeScript,你可以用它来获取任何JS的advatage
sortType(sort: string, order: string) {
    if (sort === 'name') {
        this.projects = this.projects.sort((c1: SprBitType, c2:SprBitType) => c1.name - c2.name)
        console.log(this.sprBitTypes);
    } else {
        this.projects = this.projects.sort((c1: SprBitType, c2:SprBitType) => c2.name - c1.name)
    }

}