【问题标题】:Input search filter not working on angular2输入搜索过滤器不适用于angular2
【发布时间】:2017-05-19 08:17:26
【问题描述】:

我面临以下错误:

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() 函数有什么问题?我需要导入其他东西吗? 有什么想法吗?

谢谢

/库尔

【问题讨论】:

    标签: angular2-pipe


    【解决方案1】:

    更改您的转换函数并将传递值类型修改为“任何 []”。希望对你有帮助

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

    【讨论】:

    • 出于某种原因,它无需更改一行代码即可工作。我怎么不知道!!
    【解决方案2】:

    如果你真的读过这个错误,你就会知道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());
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2020-07-17
      • 1970-01-01
      • 2019-11-11
      • 2020-12-26
      • 1970-01-01
      相关资源
      最近更新 更多