You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何为ng-bootstrap可排序表格表头配置FontAwesome排序图标

实现方案

你只需要做两处调整即可实现按需切换排序图标:

  1. 先给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});
  }
}
  1. 修改表头模板,通过模板引用变量获取当前列的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:18:02