Angular中如何为ng-bootstrap可排序表格表头配置FontAwesome排序图标
实现方案
你只需要做两处调整即可实现按需切换排序图标:
- 先给
NgbdSortableHeader指令添加exportAs配置,方便在模板中引用指令实例获取排序状态:
@Directive({ selector: 'th[sortable]', exportAs: 'NgbdSortableHeader', // 新增该行配置 host: { '[class.asc]': 'direction === "asc"', '[class.desc]': 'direction === "desc"', '(click)': 'rotate()' } }) export class NgbdSortableHeader { @Input() sortable: string = ''; @Input() direction: SortDirection = ''; @Output() sort = new EventEmitter<SortEvent>(); rotate() { this.direction = rotate[this.direction]; this.sort.emit({column: this.sortable, direction: this.direction}); } }
- 修改表头模板,通过模板引用变量获取当前列的
direction属性,控制图标显隐:
<th scope="col" sortable="firstName" (sort)="onSort($event)" #header="NgbdSortableHeader"> Name <!-- 未排序时显示默认排序图标 --> <fa-icon [icon]="faSort" *ngIf="header.direction === ''"></fa-icon> <!-- 升序时显示向上图标 --> <fa-icon [icon]="faSortUp" *ngIf="header.direction === 'asc'"></fa-icon> <!-- 降序时显示向下图标 --> <fa-icon [icon]="faSortDown" *ngIf="header.direction === 'desc'"></fa-icon> </th>
简化写法
你也可以直接动态绑定icon属性,只保留一个图标标签即可:
<th scope="col" sortable="firstName" (sort)="onSort($event)" #header="NgbdSortableHeader"> Name <fa-icon [icon]="header.direction === '' ? faSort : (header.direction === 'asc' ? faSortUp : faSortDown)" ></fa-icon> </th>
内容的提问来源于stack exchange,提问作者Nicke Manarin
相关产品推荐
相关产品推荐

