【问题标题】:Angular6 filterAngular6 过滤器
【发布时间】:2018-10-16 13:01:26
【问题描述】:

我正在尝试在 Angular 6 中构建一个过滤管道,但它无法正常工作。

.html

<form>
  <div class="form-group">
    <div class="input-group">
      <input type="text" class="form-control" name="searchString" placeholder="Type to search..." [(ngModel)]="searchString">
    </div>
  </div>
</form>
<table class="table">
  <tr *ngFor="let user of users | filter2 : searchString">
    {{user.name}}
  </tr>
</table>

管道

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

@Pipe({
  name: 'filter2'
})

export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!items) return [];
    if (!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter(it => {
      return it.toLowerCase().includes(searchText);
    });
  }
}

当我在输入中写入时出现此错误:

ERROR TypeError: it.toLowerCase 不是函数

我做错了什么?感谢您的宝贵时间!

users

【问题讨论】:

    标签: filter pipe angular6


    【解决方案1】:

    你可以试试。name.toString().toLowerCase().includes(searchText);

    组件

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'app';
      users:any[];
      constructor(){
        this.users = [
          {name:"John"},
          {name:"Tom"},
          {name:"Carlton"},
          {name:"Judy"},
          {name:"Ada"}
        ];
      }
    }
    

    HTML

    <form>
      <div class="form-group">
        <div class="input-group">
          <input type="text" class="form-control" name="searchString" placeholder="Type to search..." [(ngModel)]="searchString">
        </div>
      </div>
    </form>
    <table class="table">
      <tr *ngFor="let user of users | filter2 : searchString">
        {{user.name}}
      </tr>
    </table>
    

    管道

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'filter2'
    })
    
    export class FilterPipe implements PipeTransform {
      transform(items: any[], searchText: string): any[] {
        if (!items) return [];
        if (!searchText) return items;
        searchText = searchText.toLowerCase();
        return items.filter(it => {
          return it.name.toLowerCase().includes(searchText);
        });
      }
    }
    

    【讨论】:

    • 我已经试过了。我不会收到任何错误,但它不起作用。
    • 也许你忘了给你的组件添加管道。
    • 而且你应该使用项目的名称属性。
    • 抱歉来晚了,但我已经更新了响应,我已经尝试了这段代码并且它有效。
    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多