1

我有这个过滤器管道:

import { Pipe, PipeTransform } from '@angular/core';
import { TaskStatus } from './task-status';

@Pipe({name: 'WithStatus'})
export class TaskStatusFilter implements PipeTransform{
    transform(items: any[], args: any[]): any {
        return items.filter(item => item.status == args[0]);
    }
}

TaskStatus 是一个枚举:

export enum TaskStatus{
    New, Dev, Test, Deploy
}

现在我想通过传递枚举值在组件中使用管道。

import { Component, OnInit } from '@angular/core';
import { Task } from '../task/task';
import { TaskStatus } from '../task/task-status';

@Component({
  selector: 'app-board',
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.css']
})
export class BoardComponent implements OnInit {
  tasks: Array<Task>;
  public TaskStatus = TaskStatus;
  constructor() {
    this.tasks = [
      new Task(1,'tasl1', 'task1 description', TaskStatus.New),
      new Task(2,'tasl2', 'task2 description', TaskStatus.New),
      new Task(3,'tasl3', 'task3 description', TaskStatus.New),
      new Task(4,'tasl4', 'task4 description', TaskStatus.Dev),
      new Task(5,'tasl2', 'task2 description', TaskStatus.Dev),
      new Task(6,'tasl6', 'task6 description', TaskStatus.Test),
      new Task(7,'tasl7', 'task7 description', TaskStatus.Deploy)
    ];
  }
  ngOnInit() { }
}

board.component.html:

<div class="grid grid-pad">
  <div class="col-1-4">
    <div class="content">
      <h2>New</h2>
      <app-task-card *ngFor="let task of tasks | WithStatus: TaskStatus.New" [task]="task"></app-task-card> <!-- This does not work - the filter is false for every element  -->
    </div>
  </div>
  <div class="col-1-4">
    <div class="content">
      <h2>Development</h2>
      <app-task-card *ngFor="let task of tasks | WithStatus: '1'" [task]="task"></app-task-card> <!--passing the value of the enum works-->
    </div>
  </div>
  <div class="col-1-4">
    <div class="content">
      <h2>Test</h2>
      <app-task-card *ngFor="let task of tasks | WithStatus: '2'" [task]="task"></app-task-card>
    </div>
  </div>
  <div class="col-1-4">
    <div class="content">
      <h2>Deploy</h2>
      <app-task-card *ngFor="let task of tasks | WithStatus: '3'" [task]="task"></app-task-card>
    </div>
  </div>
</div>

如果我传递一个与枚举值相对应的字符串,如“0”、“1”等,它可以工作,但如果我传递 TaskStatus.New - 不会显示任何值。

有没有办法使用枚举作为管道参数?

4

1 回答 1

3

我猜您看到了一个旧的管道示例,原因是您的args array.

像这样写你的管道:

@Pipe({name: 'WithStatus'})
export class TaskStatusFilter implements PipeTransform{
    transform(items: any[], status: any): any {
        if (!items || !items.length) return [];
        return items.filter(item => item.status == status);
    }
}

并像他一样使用你的管道:

<app-task-card *ngFor="let task of tasks | WithStatus: TaskStatus.New" [task]="task"></app-task-card>

它与字符串一起使用,原因是'1'[0] == '1'..

.

附加信息:

使用具有多个参数的管道将是这样的:

transform(items: any[], arg1: any, arg2, arg3, ...): any

并像这样使用它:

*ngFor="let item of items | pipeName : arg1 : arg2 : arg3 : ..."
于 2016-09-21T16:55:38.317 回答