简体   繁体   English

Angular6滤镜

[英]Angular6 filter

I'm trying to build a filter pipe in Angular 6, but it's not working properly. 我正在尝试在Angular 6中构建过滤器管道,但是它无法正常工作。

.html 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>

pipe

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);
    });
  }
}

I get this error when I write inside input: 我在输入内部编写时收到此错误:

ERROR TypeError: it.toLowerCase is not a function 错误TypeError:it.toLowerCase不是函数

What am I doing wrong? 我究竟做错了什么? Thank you for your time! 感谢您的时间!

users 用户

You can try it.name.toString().toLowerCase().includes(searchText); 您可以尝试一下。name.toString()。toLowerCase()。includes(searchText);

Component 零件

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 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>

Pipe

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);
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM