New in Angular — afterNextRender and afterRender

A playful approach to exploring Angular’s new browser-only lifecycle hooks.

Eduardo Roth
HeroDevs

--

The Angular logo rendering inside of a browser frame with the HeroDevs color gradient.

As the Angular team continues to work on framework improvements like fine-grained reactivity with Signals, and partial hydration with server-side rendering (SSR), they have introduced two new hooks. These hooks will be particularly useful when we need to update the DOM with our state, but only when running in the browser.

From the Angular docs:

Sometimes it’s necessary to use browser-only APIs to manually read or write the DOM. This can be challenging to do with the lifecycle events above, as they will also run during server-side rendering and pre-rendering. For this purpose, Angular provides afterRender and afterNextRender. These functions can be used unconditionally, but will only have an effect on the browser. Both functions accept a callback that will run after the next change detection cycle (including any nested cycles) has completed.

So, this means that we now have two methods that only run in the browser, making our updates to the DOM safe even when using SSR or pre-rendering.

afterNextRender

Perform one-time initialization, or observe a single, specific change to the DOM.

This event is triggered once after the next change detection cycle that is triggered by Angular. So that makes this event perfect for any initialization code that you need in your app, for example any third-party libraries, or browser-only APIs (for example initializing ResizeObserver API).

afterRender

Synchronize state with the DOM.

Any time there’s a change detection cycle, this event will be triggered and run. This is perfect to update the DOM every time Angular detects a change. You could use it to make additional writes to (or reads from) the DOM based on an app update.

Continue Reading on HeroDevs Blog: For the full article and more in-depth insights, visit our official blog. Click here to read the complete post on HeroDevs.

About HeroDevs

HeroDevs is a software engineering and consulting studio that specializes in front-end development. Our team has authored or co-authored projects like the Angular CLI, Angular Universal, Scully, XLTS — extended long-term support for AngularJS, Vue2, Protractor, and many others. We work with fast-growing startups and some of the world’s largest companies like Google, GE, Capital One, Experian, T-Mobile, Corteva, and others. Learn more about us at herodevs.com.

--

--