I have a (click)
that calls a sortUser()
function that sorts the data. My HTML looks like this.
let isAscendingSort: Boolean = true; sortUser() { console.log('sorting!'); //just to check if sorting is beng called this.items.sort((item1: any, item2: any) => this.compare(item1, item2)); } // Sort compare(item1: any, item2: any): number { let compValue = 0; compValue = item1.attributes.fullName.localeCompare(item2.attributes.fullName, 'en', { sensitivity: 'base' }); console.log(compValue); if (!this.isAscendingSort) { compValue = compValue * -1; } return compValue; }
<button (click)="sortData()">Sort Data</button> <div *ngFor="let item of items"> {{items.attributes.fullName}} </div>
What I want is It should sort Ascending/Descending on click of a button .But it'll only sort the data based ascending oreder only.I dont know what am I doing wrong.
Seems like you are forgetting to flip the switch:
private isAscendingSort: boolean = false;
sortUser() {
console.log('sorting!'); // just to check if sorting is being called
this.isAscendingSort = !this.isAscendingSort; // you missed this
this.items.sort((item1: any, item2: any) => this.compare(item1, item2));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.