Angular 16.2: Application hooks and bindings for dynamic components
The Angular team has released version 16.2 and introduces two new features, among other things. On the one hand, the release simplifies bindings for dynamic components and, on the other hand, it brings the new application hooks afterRender and afterNextRender.
Advertisement
Simplified bindings for dynamic components
The NgComponentOutlet directive loads components dynamically. It acts as a placeholder and can only decide at runtime which component should be used at all. To date, however, this directive has been subject to restrictions. So you couldn’t easily apply property binding to the dynamic component. In Angular, property binding is the process by which parent components can pass data to their children.
In the following code example, there are two different components that the AppComponent uses depending on the time of day. Both components require the same input.
With Angular 16.2, the code now looks much simpler:
@Component({
selector: ‘app-root’,
template: `
standalone: true,
imports: (NgComponentOutlet),
})
export class AppComponent {
daylightService = inject(DaylightService);
userService = inject(UserService);
component;
context: Record
constructor() {
this.component = this.daylightService.isDay()
? WelcomeAtDayComponent
: WelcomeAtNightComponent;
const { sunrise, sunset } = this.daylightService.getSunTimes();
this.context = {
username: this.userService.username,
sunrise,
sunset,
};
}
}
Depending on the return value of isDay() of the daylightService, the property component is assigned either the WelcomeAtDayComponent or WelcomeAtNightComponent class.
Advertisement
Furthermore, context contains the values for the property binding of the two components.
Finally, the template is where the action takes place. *ngComponentOutlet loads the dynamic component in combination with inputs and carries out the property binding internally.
Application hooks as function calls
Another interesting feature are the new application hooks afterRender and afterNextRender.
Until now, hooks in Angular were only known at the component level. These are interfaces that the components can implement. Well-known examples are OnInit or OnDestroy.
The new hooks no longer refer to the component. They are also not interfaces, but normal function calls. This also makes them suitable for use in services. It is important that they run in the so-called injection context. In Angular, this is mainly the code that runs at instantiation. Methods that are only valid in the injection context are not new territory in Angular. The same rules already apply to inject or effect (signals).
Angular registers all calls to afterRender and afterNextRender and then executes them in the same order as they were registered. afterRender runs after each completed change detection cycle. This is the feature where Angular traverses the component tree and updates the DOM accordingly when the state changes.
Angular also runs afterNextRender after a change detection pass, but only once, unlike afterRender. Perhaps the term afterOneRender would have been more appropriate here.
afterNextRender is useful when a third party library needs a rendered DOM element. afterNext, on the other hand, is more likely to be used in libraries where you have to get “closer” to the framework.
Both application hooks only run in the browser and not on the server if server-side rendering is used.
The code below shows both hooks in action.
@Component({
selector: ‘app-root’,
template: ` `,
standalone: true,
})
export class AppComponent {
ngZone = inject(NgZone);
cdCounter = 0;
constructor() {
afterRender(() => {
console.log(‘CD Runs: ‘, ++this.cdCounter);
});
afterNextRender(() => {
this.ngZone.runOutsideAngular(() => {
const img = document.getElementsByTagName(‘img’)(0) as HTMLImageElement;
img.addEventListener(‘load’, () => {
if (img.naturalWidth > img.width) {
console.error(‘image too large. consider NgOptimizedImage’);
}
});
});
});
}
}
afterRender increases the internal counter with each run. The use case here is clearly analysis or debugging.
afterNextRender, on the other hand, registers for the load event of the rendered image and checks whether the dimensions of the original match those of the rendering.
In addition, there are a number of other small features and of course bug fixes in the new release. The work on server-side rendering should not go unmentioned. Angular 16.2 brings some improvements, especially in the area of the CLI.
Next major release in November
The release of Angular 17 is planned for November. According to the current status, however, developers will have to wait until Angular 18 for the announced signal component. However, in Angular 17, the current signal functionality will exit the developer preview state and become stable.
Two weeks ago, RFCs (Request for Comments) ended, which will add control structures to the template syntax. In addition, the Angular team is planning a so-called “deferred loading” of components. A component is only loaded from the server when it comes into the viewport, for example.
The extent to which these new features can already be used in version 17 remains open. In any case, the Angular framework continues to innovate unchecked.
Sample code is on GitHub to try. The release notes for Angular 16.2 can also be found there.
(May)
Go to Home
#Angular #Application #hooks #bindings #dynamic #components