angular2管不工作 [英] angular2 pipe not working
本文介绍了angular2管不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在angular2中使用搜索功能。
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;
}
}
在这之后我试图应用这个管道在这里的html:
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"
它给我以下错误:
TypeError:当我没有应用管道时,无法读取未定义的属性'0'
TypeError: Cannot read property '0' of undefined
正确打印数组元素但是只要我在html中应用搜索管道就会给我上面的错误。
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.
任何输入?
推荐答案
RC中的新管道需要多个参数而不是一个数组:
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;
}
这篇关于angular2管不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文