我已经在Angular2中的RSS feed阅读器应用程序上实现了排序,但是我的解决方案远非优雅和可扩展。在HTML中,按钮有3种状态:排序的ASC(1),排序的DESC(-1)和非活动的(0)。这有助于我管理按钮上的glyphicons,但它有很多变量跟踪,值更改和检查。我需要一些帮助来改进这个解决方案。 这是app.component中的代码:
abcSort = 0; // 0 = not sorted, 1 = sorted ascending, -1 = sorted descending
dateSort = 0; // 0 = not sorted, 1 = sorted ascending, -1 = sorted descending
onSortAbc() {
if (this.abcSort === 0 || this.abcSort === -1) {
this.feedService.sortByAbcAsc(this.feeds);
this.abcSort = 1;
} else {
this.feedService.sortByAbcDesc(this.feeds);
this.abcSort = -1;
}
this.dateSort = 0;
}
onSortDate() {
if (this.dateSort === 0 || this.dateSort === -1) {
this.feedService.sortByDateAsc(this.feeds);
this.dateSort = 1;
} else {
this.feedService.sortByDateDesc(this.feeds);
this.dateSort = -1;
}
this.abcSort = 0;
}
private resort() {
if (this.dateSort === 1) {
this.feedService.sortByDateAsc(this.feeds);
} else if (this.dateSort === -1) {
this.feedService.sortByDateDesc(this.feeds);
} else if (this.abcSort === 1) {
this.feedService.sortByAbcAsc(this.feeds);
} else if (this.abcSort === -1) {
this.feedService.sortByAbcDesc(this.feeds);
}
}
app.component.html:
<div class="btn-group">
<button [ngClass]="{'glyphicon': true, 'glyphicon-arrow-up': abcSort ==1,'glyphicon-arrow-down': abcSort ==-1 , 'active' : abcSort !=0 }"
class="btn btn-default" (click)="onSortAbc()" btnRadio="Left">Abc</button>
<button [ngClass]="{'glyphicon': true, 'glyphicon-arrow-up': dateSort == 1,'glyphicon-arrow-down': dateSort ==-1, 'active' : dateSort !=0 }"
class="btn btn-default" (click)="onSortDate()" btnRadio="Right">Date</button>
</div>
感谢。