angular2 case不敏感过滤器使用管道?

时间:2016-04-21 12:29:35

标签: json angular case-insensitive

我想知道如何使用angular2中的管道进行不区分大小写的比较。

下面是我到目前为止使用的方法。

正确搜索组件但区分大小写。

如何使其不区分大小写?

1.components.json

"components": [
  {
      "name":"HeadingComponent",
      "desc":"",
      "cmpType":"Standard",
      "imgUrl":"http://localhost:3202/uploads/ABC_bank.png",
      "cmpLocation":"",
      "isDynamic":"true"          
  },
  {
      "name":"BodyComponent",
      "desc":"",
      "cmpType":"Standard",
      "imgUrl":"http://localhost:3202/uploads/demoairline.png",
      "cmpLocation":"",
      "isDynamic":"true" 
  },
  {
      "name":"FooterComponent",
      "desc":"",
      "cmpType":"Standard",
      "imgUrl":"http://localhost:3202/uploads/SCE_5.PNG",
      "cmpLocation":"",
      "isDynamic":"true" 
  }  

在阅读此JSON数据后,我正在使用管道使用下面的代码执行搜索操作。

2.components.html

<input class="form-control input-sm" [(ngModel)]="searchComp" type="text" placeholder="Search Components..." />
<li *ngFor="#comp of record.components | search:searchComp " style="display:block;padding:0px;cursor:move;position:relative;margin-top:5px;margin-bottom:5px"
        title="{{comp.name}}">
    <p class="text-center h6" style="font-size:8px;color:blue;font-weight:bold;">
       {{comp.name }}
    </p>
    <img class="img-thumbnail1" src="{{comp.imgUrl}}" style="max-width:100%;" (click)="clicked(comp.name)">
</li>

3.search.pipe.ts

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

@Pipe({
    name: 'search',
    pure: false 
})
@Injectable()
export class SearchPipe implements PipeTransform {
    transform(components: any[], args: any): any {
        // filter components array, components which match and return true will be kept, false will be filtered out
        return components.filter((component)=>component.name.indexOf(args)!== -1);
        //return components;
    }

}

到目前为止它的工作正常但是区分大小写,我怎样才能使这个不区分大小写呢? 我试过angularjs 1逻辑为

*ngFor="#comp of record.components | search:searchComp :false"

但它没有用。 有什么建议? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

你可以尝试类似的东西:

@Pipe({
  name: 'search',
  pure: false 
})
@Injectable()
export class SearchPipe implements PipeTransform {
  transform(components: any[], args: any): any {
    var val = args[0];
    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;
  }
}

并以这种方式使用它:

*ngFor="#comp of record.components | search:searchComp:true"

请参阅此plunkr:https://plnkr.co/edit/cFNvstvWBWSG4l0UaPb2?p=preview