【发布时间】:2021-09-23 10:10:32
【问题描述】:
我正在尝试将sort、sortUp 和sortDown 图标设置为我的表格标题,遵循table tutorial from ng-bootstrap。
有一个NgbdSortableHeader 指令可以改变列的排序:
@Directive({
selector: 'th[sortable]',
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});
}
}
以及拥有表格的组件:
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.scss'],
providers: [UserService]
})
export class UsersComponent implements OnInit {
faSort = faSort;
faSortUp = faSortUp;
faSortDown = faSortDown;
users$: Observable<User[]>;
total$: Observable<number>;
@ViewChildren(NgbdSortableHeader) headers!: QueryList<NgbdSortableHeader>;
constructor() {
}
ngOnInit(): void {
}
onSort({column, direction}: SortEvent) {
// resetting other headers
this.headers.forEach(header => {
if (header.sortable !== column) {
header.direction = '';
}
});
this.service.sortColumn = column;
this.service.sortDirection = direction;
}
}
我想知道是否有办法访问当前列排序顺序并替换项目中的图标或隐藏它们。
<th scope="col" sortable="firstName" (sort)="onSort($event)">
Name
<fa-icon [icon]="faSort"></fa-icon>
<fa-icon [icon]="faSortUp"></fa-icon>
<fa-icon [icon]="faSortDown"></fa-icon>
</th>
【问题讨论】:
-
您的
UsersComponentsn-p 中的onSort处理程序已经在接收有关名称(即column)和最后交互的列的排序方向的信息。如果您将这些暴露给您的模板,那么您可以简单地使用一系列*ngIf指令来控制每个fa-icon的可见性(例如<fa-icon [icon]="faSortUp" *ngif="sortColumn === 'firstName' && sortDirection ==='asc'"></fa-icon>)。但是,这会变得冗长,因此请考虑将这些图标封装在一个聚合组件中。 -
我最初的想法(发布此问题后)是从指令中获取视图子项并更改其中的
fa-icon元素的图标。这样我就不需要更改每张表,只需一个fa-icon元素。 -
@miqh 我能够从指令中更改图标。
标签: html css angular angular-fontawesome