Last active
May 4, 2021 15:06
-
-
Save dorthrithil/9f272a3be70fd087d4829cb092587aa3 to your computer and use it in GitHub Desktop.
Angular: pipe any function in your template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Pipe that let's you pipe just anything! Function calls in your templates are normally a bad idea, performance wise. | |
* However you can get around this problem by writing pipes that don't trigger on every CD cycle but only when the arguments change. | |
* Doing this for every function you want can be painful however! Here comes arbitraryPipedFunction for the rescue! | |
* Just pass the function, the arguments, the context and some extra arguments you may want to include in the watches arguments for the | |
* pipes internal CD. There you go. One pipe to rule them all. | |
*/ | |
@Pipe({ | |
name: 'arbitraryPipedFunction' | |
}) | |
export class ArbitraryPipedFunctionPipe implements PipeTransform { | |
/** | |
* Pipes anything! | |
* Call it in your template like so: | |
* ```html | |
* <div>{{myFunction | arbitraryPipedFunction : this : [42,'sinus'] : watchMe, watchMeToo}}</div> | |
* ``` | |
* @param functionToPipe function that should get piped. | |
* @param context This context of the called function. | |
* @param args Arguments to pass to functionToPipe. | |
* @param changeDetectionArgs Arbitrary number of extra arguments to watch for changes (changes to them will trigger the pipe) | |
* computation. | |
*/ | |
transform(functionToPipe: (...args) => any, context, args: any[] = [], ...changeDetectionArgs: any[]): any { | |
return functionToPipe.bind(context)(...args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment