Having trouble filtering table contents with multiple fields? Let's take a look at the code:
https://i.sstatic.net/jfLbz.png HTML: Here is the code snippet for filtering data:
<ng-select [options]="name" [(ngModel)]="filter.name"></ng-select>
<ng-select [options]="email" [(ngModel)]="filter.email"></ng-select>
<input type="number" onKeyPress="if(this.value.length==10) return false;" class="form-textbox input-text" [(ngModel)]="filter.phone_number">
<ng-select [options]="pinAddress" [(ngModel)]="filter.address"></ng-select>
Using a pipe to filter the table:
<tbody>
<tr *ngFor="let pin of pins | pinfilter:filter">
<td>{{pin.name}}</td>
<td>{{pin.description}}</td>
<td>{{pin.address}}</td>
<td>{{pin.website}}</td>
<td>{{pin.phone_number}}</td>
<td>{{pin.email}}</td>
<td>{{pin.comments}}</td>
</tr>
</tbody>
TS:
filter.pipe.ts:
/* Tutorial filter to write filter functions for Tutorial*/
import { Pipe, PipeTransform } from '@angular/core';
export class NewPin {
public _id:number;
public user_id:number;
public name:string;
public address:string;
public phone_number:string;
public email:string;
public comments:boolean;
}
@Pipe({
name: 'pinfilter',
pure: false
})
export class PinPipe implements PipeTransform {
transform(items: NewPin[], filter: NewPin): NewPin[] {
if (!items || (!filter.name && !filter.address)) {
return items;
}
return items.filter((item: NewPin) => this.applyFilter(item, filter));
}
applyFilter(user: NewPin, filter: NewPin): boolean {
console.log(filter);
if (filter.name && filter.address) {
if (filter.name == user.name && filter.address == user.address) {
return true
} else {
return false
}
} else if (filter.name) {
if (filter.name == user.name) {
return true
} else {
return false
}
} else if (filter.address) {
if (filter.address == user.address) {
return true
} else {
return false
}
} else {
return true
}
}
}
component.ts:
public filter: NewPin = new NewPin();