客户过滤管道 - Angular2

Customer filter pipe - Angular2

在下面的组件视图中,

<h2>Topic listing</h2>

<form id="filter">
  <label>Filter topics by name:</label>
  <input type="text" [(ngModel)]="term">
</form>

<ul id="topic-listing">
  <li *ngFor="let topic of topics | filter: term">
    <div class="single-topic">
      <!-- Topic name -->
      <span [ngStyle]="{background: 'yellow'}">name - {{topic.name}}</span>
      <!-- Topic type -->
      <h3>{{topic.type}}</h3>
    </div>
  </li>
</ul>

自定义过滤器语法为:let topic of topics | filter: term

自定义过滤器是:

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

@Pipe({
  name: 'filter'
})

export class FilterPipe implements PipeTransform {

  transform(topics: any, term: any): any {
    // check if search term is undefined
    if(term === undefined) return topics;
    return topics.filter(function(topic){ // javascript filter(function)
      // if below is false, then topic will be removed from topics array
      return topic.name.toLowerCase().includes(term.toLowerCase());
    })
  }

}

组件 class 维护 topics 的数据:

export class DirectoryComponent implements OnInit {
  topics = [
    {type:"Fiction", name:"Avatar"},
    {type:"NonFiction", name:"Titanic"},
    {type:"Tragedy", name:"MotherIndia"},
  ];
  constructor() { }

  ngOnInit() {
  }

}

编辑: 没有 form 标签,代码工作正常。

  <label>Filter topics by name:</label>
  <input type="text" [(ngModel)]="term">

为什么自定义过滤器 FilterPipe 不过滤输入元素中提供的 term

为您的过滤条件添加括号

<ul id="topic-listing">
  <li *ngFor="let topic of (topics | filter: term)">
    <div class="single-topic">
      <!-- Topic name -->
      <span [ngStyle]="{background: 'yellow'}">name - {{topic.name}}</span>
      <!-- Topic type -->
      <h3>{{topic.type}}</h3>
    </div>
  </li>
</ul>

检查TS文件

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  term : any = "avatar";
  topics = [
    {type:"Fiction", name:"Avatar"},
    {type:"NonFiction", name:"Titanic"},
    {type:"Tragedy", name:"MotherIndia"},
  ];
}

删除单词函数并将其更改为以下代码。参考 working version here

return topics.filter((topic)=>{ 
      return topic.name.toLowerCase().includes(term.toLowerCase());
    })

更新 - 问题的根本原因

如果你想在表单标签中使用 NgModel,必须设置 name 属性或者表单控件必须在 ngModelOptions

中定义为 'standalone'