【发布时间】:2019-09-23 01:17:33
【问题描述】:
我正在为 Angular 组件中的发票表设置几个过滤器。一个是与来自 invoices 数组的发票模型的属性名称匹配的搜索输入,另一个是来自下拉选择元素的“状态”过滤器。
这个新过滤器只会在“statusFilter”(ngModel)不等于 0 时运行,因为 0 是默认值,意味着显示所有忽略发票的状态。我能够成功地单独过滤每个条件,但是当尝试在一个过滤器函数中添加这两个条件时,callbackfn 总是返回 false。
现在,只有在搜索输入中输入一个值后,我才能从过滤器中获得真正的结果。
HTML
<select [(ngModel)]="statusFilter" (change)="updateFilter($event)">
<option [value]="0">Show All</option>
<option [value]="4">Paid</option>
<option [value]="1">Outstanding</option>
<option [value]=8>Cancelled</option>
</select>
....
<label>Search:
<input (keyup)="updateFilter($event)" class="form-control form-control-sm" placeholder="search by name.." type="search">
</label>
组件
export class CompanyInvoicesComponent implements OnInit {
public isLoading: boolean;
public limit = 10;
public temp = [];
public selected = [];
public invoice: Invoice;
public statusFilter: number = 0;
public rows: Invoice[];
@ViewChild(DatatableComponent) table: DatatableComponent;
constructor(
private _appService: AppService,
private _invoiceService: InvoiceService,
) {
this._invoiceService.companyInvoices()
.subscribe( (invoices) => {
const invoicesArr = [];
for (const invoice of invoices) {
invoicesArr.push(new Invoice(invoice, true));
}
this.rows = invoicesArr;
this.temp = [...invoicesArr];
this._appService.toggleLoading(false);
});
}
updateFilter(event) {
const val = event.target.value.toLowerCase();
let temp = this.temp.filter((invoice) => {
// the type number is lost after value is changed.
const parsedStatusFilter = parseInt(this.statusFilter.toString(), 10);
console.log(parsedStatusFilter);
if (parsedStatusFilter == 0) {
return (invoice.name.toLowerCase().indexOf(val) !== -1 || !val);
} else {
return (parsedStatusFilter == invoice.statusNumber) && (invoice.name.toLowerCase().indexOf(val) !== -1 || !val);
}
});
// update the rows
this.rows = temp;
// Whenever the filter changes, always go back to the first page
this.table.offset = 0;
}
【问题讨论】:
标签: angular typescript