I'm trying to do something similar to this application:
https://stackblitz.com/edit/angular-table-sort-and-filter?file=src/app/app.component.ts
This is my application :
https://stackblitz.com/edit/angular-table-sort-and-filter-w9hrc3?file=src/app/app.component.html
HTML:
<thead >
<tr>
<th
*ngFor="let item of list.table.headings; let i = index"
scope="col"
sortable="{{ item.content }}"
(sort)="onSort($event, i)"
>
{{ item.content }}
</th>
</tr>
</thead>
Directive:
export type SortColumn = string | '';
export type SortDirection = 'asc' | 'desc' | '';
const rotate: { [key: string]: SortDirection } = {
asc: 'desc',
desc: '',
'': 'asc',
};
export const compare = (
v1: string | number | boolean | Date,
v2: string | number | boolean | Date
) => (v1 < v2 ? -1 : v1 > v2 ? 1 : 0);
export interface SortEvent {
column: SortColumn;
direction: SortDirection;
}
@Directive({
selector: 'th[sortable]',
host: {
'[class.asc]': 'direction === "asc"',
'[class.desc]': 'direction === "desc"',
'(click)': 'rotate()',
},
})
export class SortableHeaderDirective {
@Input() sortable: SortColumn = '';
@Input() direction: SortDirection = '';
@Output() sort = new EventEmitter<SortEvent>();
rotate() {
this.direction = rotate[this.direction];
this.sort.emit({ column: this.sortable, direction: this.direction });
}
}
An up and a down icon is appearing when the user clicks on the header of the table in the original code (first link). But in my code, it didn't appear. I don't know what I'm doing wrong.
CodePudding user response:
If you inspect the rendered <th>
element:
<th _ngcontent-hpt-c62="" scope="col" ng-reflect-sortable="Tercih"> Tercih </th>
There is no sortable
attribute, while your SortableHeaderDirective
is applied to <th>
element with sortable
attribute: 'th[sortable]'
.
With sortable="{{ item.content }}"
or [sortable]="item.content"
is used as property binding.
You can perform either of these to add the sortable
attribute:
Add
sortable
without string interpolation.Add
[attr.sortable]="item.content"
.
<th
*ngFor="let item of list.table.headings; let i = index"
scope="col"
sortable="{{ item.content }}"
(sort)="onSort($event, i)"
sortable
>
{{ item.content }}
</th>
CodePudding user response:
HTML:
<div >
<div
*ngFor="let item of this.list.table.headings; let i = index"
>
<div scope="col" (sort)="onSort($event, i, this.table)" sortable="{{ item.content }}">
{{ item.content }}
</div>
</div>
</div>
Directive:
@Directive({
selector: 'div[sortable]',
host: {
'[class.sorting]': 'true',
'[class.sorting-desc]': 'direction === "asc"',
'[class.sorting-asc]': 'direction === "desc"',
'(click)': 'rotate()',
},
})