【问题标题】:Pipes in Angular2Angular2中的管道
【发布时间】:2016-12-27 12:51:42
【问题描述】:

我正在尝试在 Angular 2 中创建我的第一个自定义管道,但似乎我在代码中遗漏了一些内容,使我无法获得所需的输出:我只想显示 Type 等于 'T 的名称'或'A':

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

@Pipe({name:"search"})
export class search{
  transform (value){
   x = [];
   x = items.filter(item => item.Type = 'T');
   x = items.filter(item => item.Type = 'A');
   return x;
  }
}

@Component({
selector: 'my-app',
Pipes: [search],
template: `
  <h1>My First Angular 2 App</h1>
  <br>
  <li *ngFor = "#c of todos.Name">{{c | search}}</li>
`
})
export class AppComponent { 

 todos = [
   {"Name":"Sleep","Type":"T"},
   {"Name":"Eat","Type":"E"},
   {"Name":"Work","Type":"T"},
   {"Name":"Jump","Type":"A"}
 ];

 }

【问题讨论】:

    标签: angular filter pipe


    【解决方案1】:

    您必须将 HTML 模板更改为下面的第一件事,例如 pipe 应该在 todos 上应用 ngFor

    template: `<h1>My First Angular 2 App</h1>
      <li *ngFor = "let c of todos | search">
        {{c.Name}}
      </li>`
    

    然后将您的Pipe 更改为下面的@eltonkamami 已经建议

    @Pipe({name:"search"})
    export class search implements PipeTransform{
       transform (items){
          return items.filter(item => item.Type == 'T' || item.Type == 'A');
       }
    }
    

    Demo Here

    【讨论】:

    • 我仍然没有得到任何输出,如果管道在独立文件中,你能告诉我导入管道的正确方法是什么吗?
    • 你检查过我的 plunkr 吗?你在使用 NgModule 吗?
    【解决方案2】:

    您必须像这样组合您的 Array#filter 功能

    @Pipe({name:"search"})
    export class search implements PipeTransform{
      transform (value){
        return items.filter(item => item.Type == 'T' || item.Type == 'A');
      }
    }
    

    只要items 是一个数组,Array#filter 将始终返回一个数组,因此无需将 x 设置为空数组。

    你现在的做法。
    1. 您将 x 设置为一个空数组
    2. x 是所有类型为T的项目
    3. x 是所有类型为A 的项目

    所以 x 将始终拥有类型为 A 的项目(如果没有,则为空)

    【讨论】:

    • html页面中不显示名称:(
    猜你喜欢
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2016-11-07
    相关资源
    最近更新 更多