输入搜索过滤器不在angular2上工作

时间:2017-05-19 08:17:27

标签: angular2-pipe

我面临以下错误:

EXCEPTION: Error in ./UserComponent class UserComponent - inline template:217:14 caused by: Cannot read property 'toLowerCase' of undefined

它只是一个带有搜索输入页面的用户列表。 模板如下:

<tr *ngFor="let user of users | sUser: TxtSearch">
            <td>{{user.userid}}</td>
            <td>{{user.username}}</td>
            <td>{{user.email}}</td>
            <td>{{user.fullname}}</td>
            <td>
              <button class="btn btn-warning btn-circle-sm" (click)="showEditUser(i, user._id,user)"><span class="glyphicon glyphicon-edit"></span></button>
            </td>
            <td>
              <button class="btn btn-danger btn-circle-sm" (click)="showRemoveUser(user._id, user.username)"><span class="glyphicon glyphicon-remove"></span></button>
            </td>
          </tr>

搜索输入按钮是:

<div class="input-group-addon"><i class="fa fa-search"></i></div>
<input type="text" class="form-control rounded" placeholder="Search" [(ngModel)]="TxtSearch">

管道是:

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

@Pipe({
  name: 'sUser'
})
export class UserPipe implements PipeTransform {

  transform(value: any, args?: any): any {
     if(args === undefined || args === '') return value;
    return value.filter(function(val){
      return val.username.toLowerCase().includes(args.toLowerCase());
    });
  }

}

管道/过滤器声明在app.module

管道中的toLowerCase()函数有什么问题?我需要导入别的东西吗? 有什么想法吗?

谢谢

/ Koul

2 个答案:

答案 0 :(得分:0)

更改转换功能并将传递值类型修改为“any []”。希望它有所帮助

 transform(value: any[], args?: any): any {
    if(args === undefined || args === '') 
     return value;
   return value.filter(function(val){
       return val.username.toLowerCase().includes(args.toLowerCase());
     });
   }

答案 1 :(得分:0)

如果您确实阅读了错误,那么您知道val.usernameundefined。因此,在尝试致电toLowerCase()之前,请先检查一下。您还可以为args添加安全检查:

  transform(value: any[], args?: any): any[] {

    if(args === undefined || args === '') return value;

    return value.filter(function(val) {

      if (!val.username || !args) return false;

      return val.username.toLowerCase().includes(args.toLowerCase());
    });
  }