Performant calls to pure functions in Angular Templates / Bindings
npm install ngx-function-expressionts
@Component({
template: '{{pow | fnApply:[3, 2]}}' // will render '9'
})
class TestComponent {
public pow(base: number, exponent: number): number {
return Math.pow(base, exponent);
}
}
`
Obviously, this could also be achieved by implementing a PowerPipe or precalculating the values in the component
rather than in the template, and, most of the time, this is exactly what you _should_ do!
But in reality, people will not write a pipe for every operation, or some methods are better contained in a component to access the context of that component.
$3
As with any Angular pipe, you can chain them together to receive exactly the results you want.
`ts
@Component({
template: Explosion in {{createCountdown | fnApply | async}}
})
class TestComponent {
createCountdown(): Observable {
return interval(1000).pipe(take(5), map(i => 5 - i));
}
}
`
When looking at this example, note that using {{createCountdown() | async}} would result in the AsyncPipe
subscribing to a whole new observable in every tick, keeping the countdown on 5 forever.
Using fnApply will call the method exactly once and then listen to changes on the returned observable using AsyncPipe.
Just imagine you have some XHR request or costly computations in the observable you're subscribing to...
*
You can check out more examples and the full
README over at GitHub
Get Started!
1. Run npm install ngx-function-expression
1. Add the FunctionExpressionModule to your application and use the pipes fnApply and fnMethod` in your templates.