table-sort.directive.ts:
import { Directive, Input, Output, EventEmitter } from '@angular/core';
import { OrderByPipe } from './order-by.pipe';
@Directive({
selector: '[tableSort]'
})
export class TableSortDirective {
@Input('tableSort')
data: any[] = [];
@Output()
sorted: EventEmitter = new EventEmitter();
private currentSortColumn: string = '';
private isSortAscending: boolean = true;
constructor(private orderByPipe: OrderByPipe) {}
sort(column: string) {
if (this.currentSortColumn === column) {
this.isSortAscending = !this.isSortAscending;
} else {
this.currentSortColumn = column;
this.isSortAscending = true;
}
const order: string = this.isSortAscending ? 'asc' : 'desc';
const sortedData = this.orderByPipe.transform(this.data, this.currentSortColumn, order);
this.sorted.emit(sortedData);
}
}
order-by.pipe.ts:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(data: any[], column: string, order: string): any[] {
if (!data) {
return data;
}
return data.sort((a: any, b: any) => {
const aValue = a[column];
const bValue = b[column];
if (aValue === bValue) {
return 0;
}
if (aValue > bValue) {
return order === 'asc' ? 1 : -1;
} else {
return order === 'asc' ? -1 : 1;
}
});
}
}
table.component.html:
Name
Age
{{ row.name }}
{{ row.age }}
table.component.ts:
import { Component } from '@angular/core';