如何使用多个参数调用 Angular 2 管道? [英] How do I call an Angular 2 pipe with multiple arguments?
问题描述
我知道我可以这样调用管道:
I know I can call a pipe like this:
{{ myData | date:'fullDate' }}
这里的日期管道只接受一个参数.从组件的模板 HTML 和直接在代码中调用具有更多参数的管道的语法是什么?
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?
推荐答案
在组件的模板中,您可以使用冒号分隔多个参数:
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 及之前 (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];
...
}
}
这篇关于如何使用多个参数调用 Angular 2 管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!