angular2 pipe not working

非 Y 不嫁゛ 提交于 2019-12-23 04:56:30

问题


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:


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;
}


来源:https://stackoverflow.com/questions/38201684/angular2-pipe-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!