angular2 pipe not working

2019-06-14 08:26发布

I am trying to have search functionality in angular2.

So far i have created my own custom pipe for this like below:

search.pipe.ts

import { Pipe, PipeTransform ,Injectable} from '@angular/core';

@Pipe({
    name: 'search',
    pure: false
})
@Injectable()
export class SearchPipe implements PipeTransform {
    transform(components: any[], args: any): any {
        var val = args[0];
        if (val !== undefined) {
            var lowerEnabled = args.length > 1 ? args[1] : false;

            // filter components array, components which match and return true will be kept, false will be filtered out
            return components.filter((component) => {
                if (lowerEnabled) {
                    return (component.name.toLowerCase().indexOf(val.toLowerCase()) !== -1);
                } else {
                    return (component.name.indexOf(val) !== -1);
                }
            });
       }
       return components;
    }
}

and after doing this I am trying to apply this pipe inside html like this:

*ngFor="let aComponent of selectedLib.componentGroups[groupCounter].components | search:searchComp:true"

its giving me below error:

TypeError: Cannot read property '0' of undefined

when I am not applying pipe , *ngFor prints the array elements correctly but as soon as I am applying search pipe in html its giving me above error.

any inputs?

1条回答
萌系小妹纸
2楼-- · 2019-06-14 09:15

The new pipes in RC take several arguments instead of just one array:

transform(components: any[], searchComponent: any, caseInsensitive: boolean): any {
    if (searchComponent !== undefined) {
        // filter components array, components which match and return true will be kept, false will be filtered out
        return components.filter((component) => {
            if (caseInsensitive) {
                return (component.name.toLowerCase().indexOf(searchComponent.toLowerCase()) !== -1);
            } else {
                return (component.name.indexOf(searchComponent) !== -1);
            }
        });
   }
   return components;
}
查看更多
登录 后发表回答