我有一个引导html表(由ngbootstrap为angular提供支持,并使用NgbdSortableHeader通过列单击对表列进行排序(。当我单击元素时,它会按升序、降序或''(无(对列进行排序。
HTML表格标题
<tr>
<th scope="col">#</th>
<th scope="col" sortable="name" (sort)="onSort($event)">Country</th>
<th scope="col" sortable="area" (sort)="onSort($event)">Area</th>
<th scope="col" sortable="population" (sort)="onSort($event)">Population</th>
</tr>
分拣方法
@ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;
onSort({ column, direction }: SortEvent) {
// resetting other headers
this.headers.forEach(header => {
if (header.sortable !== column) {
header.direction = "";
}
});
// sorting countries
if (direction === "") {
this.countries = COUNTRIES;
} else {
this.countries = [...COUNTRIES].sort((a, b) => {
const res = compare(a[column], b[column]);
return direction === "asc" ? res : -res;
});
}
}
每当onSort通过列标题点击触发时,它就会对国家数组进行排序并更新表。
ngOnInit() {
this.onSort({ column: "population", direction: "asc" });
}
但是当这个onSort方法在onInit((中调用时,它不起作用。如何通过调用onSort函数以程序方式实现此操作?
工作堆叠litz示例:https://stackblitz.com/edit/ngbootstrap-table-sorting-vfwu4m?file=app/table-可分拣.ts
您需要使用AfterViewInit
而不是OnInit
,因为在调用OnInit
时尚未渲染表。AfterViewInit
是在组件(和任何子组件(渲染后调用的,因此表将能够在该点进行排序(ref:https://angular.io/guide/glossary#lifecycle-挂钩(。
如果你想在程序排序时显示方向箭头,你还需要更改进行排序的代码:
this.onSort({ column: "population", direction: "asc" });
至:
let populationHeader = this.headers.find(h => h.sortable === "population");
populationHeader.sort.emit({ column: "population", direction: "asc" });
populationHeader.direction = "asc";
行populationHeader.direction = "asc";
将确保您在表的标题列上获得排序箭头。
这意味着NgbdTableSortable
变成:
export class NgbdTableSortable implements AfterViewInit {
ngAfterViewInit() {
console.log("afterViewInit working");
let populationHeader = this.headers.find(h => h.sortable === "population");
populationHeader.sort.emit({ column: "population", direction: "asc" });
populationHeader.direction = "asc";
}
...
}
请参阅此Stacklitz演示。