【问题标题】:Customer filter pipe - Angular2客户过滤管 - Angular2
【发布时间】:2018-04-29 16:30:09
【问题描述】:

在下面的组件视图中,

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

【问题讨论】:

  • 用管道名称发布您的完整代码
  • @Sajeetharan 缺少哪个代码?

标签: html forms angular angular-pipe


【解决方案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"},
  ];
}

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

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

更新 - 问题的根本原因

如果你想在表单标签中使用 NgModel,要么必须设置 name 属性,要么必须在 ngModelOptions 中将表单控件定义为“独立”

【讨论】:

  • 编辑了我的答案。我完全不知道为什么它不适用于 word 功能。
  • 您的 StackBlitz 示例也适用于 function 关键字,因此它必须是其他不同的东西。
  • @serpent5 使用 lambda 表达式对我不起作用
  • 这就是我所期望的。仔细比较您与@PrithiviRaj 的示例,看看有什么不同。
  • 我还对 HTML 进行了一项更改。请试试这个并告诉我
猜你喜欢
  • 2016-12-29
  • 2017-10-04
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多