I'm setting up a couple of filters for an invoices table in an Angular component. One is a search input that matches with the property name of an invoice model from an invoices array the other one is a "status" filter from a drop-down select element.
this new filter will only run when the "statusFilter" (ngModel) is not equal to 0, since 0 is the default and means to show all ignoring the status of the invoice. I am successfully able to filter each condition individually but when trying to add both conditions within one filter function the callbackfn always returns false.
Right now, only after enter a value in the search input is when I get true results from the filter.
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>
Component
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;
}