Appendix A: Passing Multiple Parameters to Pipe
If we ever need to pass parameters to a Pipe here is how we'd write the pipe's trasnform()
method:
transform(todos:Array <Todo>, filter: string){}
The above pipe takes two parameters, an array of todos and a filter string that we use to filter the todo.content
on. Here is the complete Pipe code:
import { Pipe, PipeTransform } from '@angular/core';
import { Todo } from './todo';
@Pipe({name: 'todoFilter'})
export class TodoFilterPipe implements PipeTransform {
transform(todos:Array <Todo>, filter: string) {
if(filter)
return todos.filter(todo => todo.content.startsWith(filter));
return todos;
}
}
For reference here is the Todo
class:
export class Todo {
content: string,
done: boolean,
}
and here is how it will used in the template:
<todo-item *ngFor="let todo of todos | todoFilter: userInput" [todo]="todo"></todo-item>
Now lets enhance this pipe so it filters on both the content and the done flag. We might be tempted to use an array to pass parameters like this:
transform(todos:Array <Todo>, params: Array<any>){}
<todo-item *ngFor="let todo of todos | todoFilter: [userInput, hideDone]" [todo]="todo"></todo-item>
Wait! this is not a good approach since we would would lose named parameters in the transform()
method.
We can do better than that since the parameters to the transform()
method is defined as TypeScript rest parameters. Our transform()
method would then become:
transform(todos:Array <Todo>, filter: string, includeDone:boolean){}
In the template here is how we pass multiple parameters:
<todo-item *ngFor="let todo of todos | todoFilter: userInput: doneSelected" [todo]="todo"></todo-item>
Note the parameters are seperated by a colon :
.
With rest parameters you can pass as many parameters as you want to and still be able to access them by name instead of passing in a array of parameters and accessing them by index.