angular2管道不工作
angular2 pipe not working
我正在尝试在 angular2 中使用搜索功能。
到目前为止,我已经为此创建了自己的自定义管道,如下所示:
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 内应用此管道,如下所示:
*ngFor="let aComponent of selectedLib.componentGroups[groupCounter].components | search:searchComp:true"
它给我以下错误:
TypeError: Cannot read property '0' of undefined
当我不应用 pipe 时,*ngFor 会正确打印数组元素,但是一旦我在 html 中应用搜索管道,它就会给我上面的错误。
有任何输入吗?
RC 中的新管道接受多个参数,而不仅仅是一个数组:
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 中使用搜索功能。
到目前为止,我已经为此创建了自己的自定义管道,如下所示:
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 内应用此管道,如下所示:
*ngFor="let aComponent of selectedLib.componentGroups[groupCounter].components | search:searchComp:true"
它给我以下错误:
TypeError: Cannot read property '0' of undefined
当我不应用 pipe 时,*ngFor 会正确打印数组元素,但是一旦我在 html 中应用搜索管道,它就会给我上面的错误。
有任何输入吗?
RC 中的新管道接受多个参数,而不仅仅是一个数组:
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;
}