尝试在 ngx-datatables 中为所有列设置过滤器选项,但不起作用。我已经编写了代码,但 i9s 无法正常工作。我在代码中犯了错误的地方。任何人都可以帮助我找到解决方案。
app.component.html:
<label> Name </label>
<input
#name
id="search"
type="text"
class="form-control"
placeholder="Search"
aria-label="Search"
aria-describedby="basic-addon1"
/>
<label> Company </label>
<input
#company
id="search"
type="text"
class="form-control"
placeholder="Search"
aria-label="Search"
aria-describedby="basic-addon1"
/>
<label> Date </label>
<input
#date
id="search"
type="text"
class="form-control"
placeholder="Search"
aria-label="Search"
aria-describedby="basic-addon1"
/>
<button (click)="updateTable()"> Search </button>
<ngx-datatable #table class="bootstrap ngx-datatable" [columns]="columns" [rows]="rows" [columnMode]="'force'"
[headerHeight]="35" [rowHeight]="'auto'" [footerHeight]="50" [limit]="10">
</ngx-datatable>
app.component.ts:
updateTable() {
let filterName = this.name.nativeElement.value
.toString()
.toLowerCase()
.trim();
let filterCompany = this.company.nativeElement.value
.toString()
.toLowerCase()
.trim();
let filterDate = this.date.nativeElement.value
.toString()
.toLowerCase()
.trim();
this.rows = this.filteredData.filter(item => {
for (let i = 0; i < this.columnsWithSearch.length; i++) {
var colValue = item[this.columnsWithSearch[i]];
if (
!filterName ||
!filterCompany ||
!filterDate ||
(!!colValue &&
colValue
.toString()
.toLowerCase()
.indexOf(filterName) !== -1)
) {
return true;
}
}
});
}
答案 0 :(得分:0)
您的主要问题在于您的病情:
if (
!filterName ||
!filterCompany ||
!filterDate ||
(!!colValue &&
colValue
.toString()
.toLowerCase()
.indexOf(filterName) !== -1)
)
如果您的 3 个字段(filterName、filterCompany 或 filterDate)之一为空,则您的过滤器将返回 true。此外,您只搜索与 filterName
您可以用对象 filter = {name: '', company: '', date: ''}
替换您的 3 个变量,然后将您的条件更改为:
const filterValue = filter[this.columnsWithSearch[i]];
if (
!filterValue ||
(!!colValue &&
colValue
.toString()
.toLowerCase()
.indexOf(filterValue) !== -1)
) {
return true;
}
另外,为了获得更清晰的代码,我建议您查看 Angular pipe,它可以让您拥有更优化的系统并添加“实时”搜索。