客户过滤器管道 - Angular2

时间:2017-11-16 08:07:58

标签: html5 forms angular angular-pipe

在以下组件视图中,

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

}

组件类维护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

1 个答案:

答案 0 :(得分:1)

为过滤条件添加括号

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