我需要有一个位于Ngx数据表上方的下拉框,该下拉框需要按下拉框中的值对Ngx数据表进行排序。我对Angular还很陌生,所以我发现在component.html中使用ngx-datatable是错误的。如何启动datatable,以便可以根据下拉框中的值对行进行排序?
考虑到component.ts中的方法链接到数据表,我打算在下拉框中调用该方法来对其进行排序。这是完全不同的!
component.html
<ngx-datatable class="expandable"
[rows]="rows"
[columns]="columns"
[headerHeight]="40"
[rowHeight]="'auto'"
[columnMode]="'force'" [limit]="20" [footerHeight]="50">
<ngx-datatable-column name="Header">
<ng-template let-value="value" let-row="row" ngx-datatable-cell-template>
<span class="custom-cell"><a (click)="method(content, id, false)">{{value}}</a></span>
</ng-template>
</ngx-datatable-column>
我的下拉框
<div ngbDropdown class="filter-dropdown-wrapper">
<button class="btn btn-light filter-button" id="input1" ngbDropdownToggle>Select an option</button>
<div ngbDropdownMenu aria-labelledby="inputmethod">
<!--<select (change)="getColumnNames($event.target.value)">
<option *ngFor="let element of rows" value="{{element.header}}"></option>
</select>-->
component.ts
columns = [
{ prop: 'header', name: 'Header' },
{ prop: 'notrelavant', name: 'Not Relevant' }, ];
我需要的是:在下拉框中的标题值的点击排序数据表。
发布于 2019-05-09 00:48:30
我为你想出了一个解决方案。如果我们分解步骤,实际上并不是很困难:
1)在ngbDropdown
上,我们用数据表的列填充菜单项。我们在每个菜单项上附加一个click
事件绑定,并将它们绑定到sort()
方法,该方法接受列属性(column.prop
)作为参数。
<div ngbDropdown class="d-inline-block">
<button class="btn btn-light filter-button" id="input1" ngbDropdownToggle>Select an option</button>
<div ngbDropdownMenu aria-labelledby="inputmethod">
<button ngbDropdownItem *ngFor="let column of columns" (click)="sort(column.prop)">
{{ column.prop }}
</button>
</div>
</div>
2)现在,在我们的component.ts上,我们定义了sort()
方法。rows
表示数据表中的数据。我们使用localeCompare按字母数字顺序对其进行排序。我们创建一个rows
的浅拷贝来显式地触发数据表中的change detection,以更新数据的顺序。
sort(prop) {
this.rows.sort((a, b) => a[prop].localeCompare(b[prop], 'en', { numeric: true }));
this.rows = [...this.rows];
}
我已经在here上创建了一个工作演示。希望对我的解释有所帮助!
https://stackoverflow.com/questions/56031477
复制相似问题