Javascript 如何使用多个参数调用 Angular 2 管道?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36816788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:35:49  来源:igfitidea点击:

How do I call an Angular 2 pipe with multiple arguments?

javascriptangularangular2-pipe

提问by Eran Shabi

I know I can call a pipe like this:

我知道我可以这样调用管道:

{{ myData | date:'fullDate' }}

Here the date pipe takes only one argument. What is the syntax to call a pipe with more parameters, from component's template HTML and directly in code?

这里的日期管道只接受一个参数。从组件的模板 HTML 和直接在代码中调用具有更多参数的管道的语法是什么?

回答by Eran Shabi

In your component's template you can use multiple arguments by separating them with colons:

在组件的模板中,您可以通过用冒号分隔来使用多个参数:

{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}

From your code it will look like this:

从您的代码来看,它将如下所示:

new MyPipe().transform(myData, arg1, arg2, arg3)

And in your transform function inside your pipe you can use the arguments like this:

在管道内的转换函数中,您可以使用如下参数:

export class MyPipe implements PipeTransform { 
    // specify every argument individually   
    transform(value: any, arg1: any, arg2: any, arg3: any): any { }
    // or use a rest parameter
    transform(value: any, ...args: any[]): any { }
}

Beta 16 and before (2016-04-26)

Beta 16 及之前 (2016-04-26)

Pipes take an array that contains all arguments, so you need to call them like this:

管道采用一个包含所有参数的数组,因此您需要像这样调用它们:

new MyPipe().transform(myData, [arg1, arg2, arg3...])

And your transform function will look like this:

您的转换函数将如下所示:

export class MyPipe implements PipeTransform {    
    transform(value:any, args:any[]):any {
        var arg1 = args[0];
        var arg2 = args[1];
        ...
    }
}

回答by Eugene

You're missing the actual pipe.

你错过了实际的管道。

{{ myData | date:'fullDate' }}

Multiple parameters can be separated by a colon (:).

多个参数可以用冒号 (:) 分隔。

{{ myData | myPipe:'arg1':'arg2':'arg3' }}

Also you can chain pipes, like so:

您也可以链接管道,如下所示:

{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}

回答by Günter Z?chbauer

Since beta.16 the parameters are not passed as array to the transform()method anymore but instead as individual parameters:

从 beta.16 开始,参数不再作为数组传递给transform()方法,而是作为单独的参数:

{{ myData | date:'fullDate':'arg1':'arg2' }}


export class DatePipe implements PipeTransform {    
  transform(value:any, arg1:any, arg2:any):any {
        ...
}

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

pipes now take a variable number of arguments, and not an array that contains all arguments.

管道现在采用可变数量的参数,而不是包含所有参数的数组。

回答by user3777549

I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.

我在 Angular 2+ 中使用 Pipes 来过滤对象数组。以下需要多个过滤器参数,但如果满足您的需要,您可以只发送一个。这是一个StackBlitz 示例。它将找到您要过滤的键,然后按您提供的值进行过滤。它实际上很简单,如果它听起来很复杂其实并不复杂,请查看StackBlitz 示例

Here is the Pipe being called in an *ngFor directive,

这是在 *ngFor 指令中调用的管道,

<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
  Hello {{item.first}} !
</div>

Here is the Pipe,

这是管道,

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

@Pipe({
  name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
  transform(myobjects: Array<object>, args?: Array<object>): any {
    if (args && Array.isArray(myobjects)) {
      // copy all objects of original array into new array of objects
      var returnobjects = myobjects;
      // args are the compare oprators provided in the *ngFor directive
      args.forEach(function (filterobj) {
        let filterkey = Object.keys(filterobj)[0];
        let filtervalue = filterobj[filterkey];
        myobjects.forEach(function (objectToFilter) {
          if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
            // object didn't match a filter value so remove it from array via filter
            returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
          }
        })
      });
      // return new array of objects to *ngFor directive
      return returnobjects;
    }
  }
}

And here is the Component containing the object to filter,

这是包含要过滤的对象的组件,

import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  items = [{ title: "mr", first: "john", last: "jones" }
   ,{ title: "mr", first: "adrian", last: "jacobs" }
   ,{ title: "mr", first: "lou", last: "jones" }
   ,{ title: "ms", first: "linda", last: "hamilton" }
  ];
}

StackBlitz Example

StackBlitz 示例

GitHub Example: Fork a working copy of this example here

GitHub 示例:在此处 Fork 此示例的工作副本

*Please notethat in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.

*请注意,在 Gunter 提供的答案中,Gunter 指出数组不再用作过滤器接口,但我搜索了他提供的链接,但没有发现任何与该声明相关的内容。此外,提供的 StackBlitz 示例显示此代码在 Angular 6.1.9 中按预期工作。它将在 Angular 2+ 中工作。

Happy Coding :-)

快乐编码:-)

回答by Sharan

Extended from : user3777549

扩展自:user3777549

Multi-value filter on one set of data(reference to title key only)

一组数据的多值过滤器(仅参考标题键)

HTML

HTML

<div *ngFor='let item of items | filtermulti: [{title:["mr","ms"]},{first:["john"]}]' >
 Hello {{item.first}} !
</div>

filterMultiple

过滤倍数

args.forEach(function (filterobj) {
    console.log(filterobj)
    let filterkey = Object.keys(filterobj)[0];
    let filtervalue = filterobj[filterkey];
    myobjects.forEach(function (objectToFilter) {

      if (!filtervalue.some(x=>x==objectToFilter[filterkey]) && filtervalue != "") {
        // object didn't match a filter value so remove it from array via filter
        returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
      }
    })
  });