Here I will be discussing about doing a simple sort using Angular and JavaScript. Let us create a simple table with an option to select sortable fields.
Component code
import { Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
item : any[];
keys : any[];
constructor(){
this.item = [
{firstName :'Prashobh',lastName : 'PS',age:28},
{firstName :'Abraham',lastName : 'A',age:38},
{firstName :'Zian',lastName : 'Z',age:16},
{firstName :'Catherin',lastName : 'CZ',age:24},
]
this.keys = Object.keys(this.item[0]);
}
}
Html
<select class="selectClass" [(ngModel)]="selected" (change)="onChange($event.target.value)">
<option [ngValue]="no-value" disabled selected>Select</option>
<option *ngFor="let k of keys">{{k}}</option>
</select>
<table class="table">
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let l of item">
<td>{{l.firstName}}</td>
<td>{{l.lastName}}</td>
<td>{{l.age}}</td>
</tr>
</tbody>
</table>
We have created a simple table along with a select box to select sortable fields. And below is our simple sort method.
onChange(value: string) {
this.item.sort(function (a, b) {
if (a[value] < b[value]) {
return -1;
}
if (a[value] > b[value]) {
return 1;
}
return 0;
});
}
We are done. Select the field in select box to sort the table.
Here we have discussed about implementing a simple sort using Angular and JavaScript.
Related Info
1. How to show a date is today or yesterday or last week etc using pipe - Angular
2. Disable submit button until all mandatory fields are filled - Angular
3. Angular client side pagination.
4. Angular show more/less pagination
No comments :
Post a Comment