My goal is to create a filter interface in Angular2 using pipes. Here's how I have implemented it:
export interface IFilterable{
passesFilter(f : string, isFilter: boolean): boolean;
}
The implementation of the interface is seen in the following Server class:
import {IFilterable} from './i-filterable';
import {Contains} from '../helpers/pipe-helpers';
export class Server extends Dto implements IFilterable {
name: string;
hostname: string;
ips: string;
operatingSystem: string;
sitesCount: number;
databasesCount: number;
passesFilter(f: string, isFilter: boolean): boolean {
console.log('in server');
if (!f || f === '') return isFilter;
f = f.toLowerCase();
return Contains(this.name, f) ||
Contains(this.hostname, f) ||
Contains(this.ips, f) ||
Contains(this.operatingSystem, f);
}
}
The pipe used for filtering looks like this:
import { Pipe, PipeTransform } from '@angular/core';
import {Contains} from '../helpers/pipe-helpers';
import {IFilterable} from '../models/i-filterable';
@Pipe({ name: 'serverFilter' })
export class ServerFilterPipe implements PipeTransform {
transform(values: IFilterable[], search: string, isFilter: boolean): IFilterable[] {
console.log(search + ' search' + isFilter + values);
return values.filter(value => {
console.log(value.passesFilter);
return value.passesFilter(search, isFilter)
});
}
}
However, I am facing issues as the second console.log in the pipe prints undefined and passesFilter function is not being called. Additionally, an error message "TypeError: setting a property that has only a getter" is encountered.
I then attempted to implement the same functionality using an abstract class instead of an interface:
export abstract class Dto {
abstract passesFilter(f: string, isFilter: boolean): boolean;
}
This alternative approach was applied to the Server class as well:
import {Dto} from './dto';
import {Contains} from '../helpers/pipe-helpers';
export class Server extends Dto {
name: string;
hostname: string;
ips: string;
operatingSystem: string;
sitesCount: number;
databasesCount: number;
passesFilter(f: string, isFilter: boolean): boolean {
console.log('in server');
if (!f || f === '') return isFilter;
f = f.toLowerCase();
return Contains(this.name, f) ||
Contains(this.hostname, f) ||
Contains(this.ips, f) ||
Contains(this.operatingSystem, f);
}
}
Here is the updated implementation of the pipe with the abstract class:
import { Pipe, PipeTransform } from '@angular/core';
import {Dto} from '../models/dto';
@Pipe({ name: 'serverFilter' })
export class ServerFilterPipe implements PipeTransform {
transform(values: Dto[], search: string, isFilter: boolean): Dto[] {
console.log(search + ' search' + isFilter + values);
return values.filter(value => {
console.log(value.passesFilter);
return value.passesFilter(search, isFilter)
});
}
}
Lastly, the helper function Contains used in the process:
export function Contains(val: string, cmp: string) {
return val ? val.toLowerCase().indexOf(cmp) >= 0 : false;
}