Angular — Why you should (and how to) avoid Function.prototype.bind in template

Liu Ting Chun
3 min readOct 27, 2020

Function.prototype.bind is a built-in function, which creates a new function with the context bound to the context given from the parameter. The major use case for this function in Angular template is the property binding (@Input) of function.

<app-test-component 
[testFunction]="printValue.bind(this)"></app-test-component>

This helps to maintain the context scope when the function is executed inside the component. It is a relatively uncommon function nowadays that some Angular developers may not have even seen it before. Yet, if you have been using it in your templates, I highly recommend you to stop doing that as it leads to performance issue.

Image from SecurEdge

The Issue

In short, the root problem is that function calls in template are not friendly to the Angular change detection mechanism. Each time change detection is triggered, all the function calls in template will always be re-executed, which includes Function.prototype.bind. For a more detailed explanation, please check out another article I have written previously:

--

--

Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.