What Happens When You Pass an Inline Object as Input to an Angular OnPush Component

Netanel Basal
Netanel Basal
Published in
2 min readMay 31, 2021

--

One of my colleagues recently asked me a question — I’m consuming an onPush component, let’s call it FooComponent, and passing an inline object to one of its inputs:

Angular runs a change detection cycle for the AppComponent. Does Angular create a new object, forcing the FooComponent to be checked?

Well, it depends. In our case, when Angular compiles the template, it notices that our object is static, and it doesn’t use any bindings. Therefore, Angular will create it once, cache it, and always return the same reference on subsequent checks.

If we take a look at the compiled code, we’ll see that Angular uses the pureFunction0 function, which does what we described above:

Let’s move to our next example, where one of the object properties value isn’t static:

Angular is efficient. In our case, it doesn’t care about the object itself. When the Angular compiler sees a binding, it’ll store its value inside the LView data structure. In our code, we have one binding, so Angular will use the pureFunction1 version:

This function will return the cached object reference if the current position value is the same as the cached one. Otherwise, it’ll return a new object contains the updated property value.

The resulting object will get passed to the ɵɵproperty function, which uses the Object.is function to check whether it needs to update the property.

To conclude, the only drawback when using an inline object over a component’s property is that the compiler will produce and execute extra code. In most cases, I’d not take it as a valid reason not to use it.

🚀 In Case You Missed It

Here are a few of my open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • error-tailor — Seamless form errors for Angular applications
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests
  • Error Tailor — Seamless form errors for Angular applications

And many more!

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.