how to apply sorting on array object in angular2/4/5 based on drop-down option(A-Z) &(Z-A)




Asked on October 19, 2018
app.component.html
-----------------------------------------------
<select id="sort-by" name="sort">
<option>Name(A to Z)</option>
<option>Name(Z to A)</option>
<option>Category(A to Z)</option>
<option>Category(Z to A)</option>
</select>
------------------------------------------------------
service.ts

Injectable({
providedIn: 'root'
})
export class WidgetService {

constructor() { }

getwidgets(): Widget[] {
return [
{

name: 'My Management',
category: 'xyz'
},
{

name: 'hospital Management',
category: 'AMD'
},
{

name: 'college Management',
category: 'xyz'
},
{
name: 'library Management',
category: 'AMD'
}];
}


}
--------------------------------------------------------------
app.component.ts

in this file i want to write sorting function based on selected option



Replied on October 19, 2018
You can try JavaScript sort() method.

Suppose you want to create sort function for name.

function compareToSort(ob1,ob2) {
  if (ob1.name < ob2.name)
    return -1;
  if (ob1.name > ob2.name)
    return 1;
  return 0;
}

Use sort() method.

getwidgets().sort(compareToSort);



Replied on October 20, 2018
Thanks Krish for quick reply with solution . do you have any idea to bind select  drop-down option  to this method in angular..  please reply

Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us