ResizeObserver in Angular: A Complete Guide
In modern web applications, responsive design is crucial. Sometimes, you need to react to changes in an element’s size dynamically. The ResizeObserver API provides a way to observe changes to the dimensions of DOM elements efficiently. In this blog, we’ll explore how to use ResizeObserver in Angular applications.
What is ResizeObserver?
ResizeObserver is a JavaScript API that allows you to observe changes in the size of DOM elements. Unlike traditional methods (such as listening to window.resize), ResizeObserver is more performant because it only tracks specific elements rather than the entire viewport.
Key Features:
- Efficiently tracks size changes of observed elements.
- Works with
display: none,flex,grid, and other CSS layouts. - Provides the new dimensions (
contentRect) of the observed element.
Using ResizeObserver in Angular
Angular doesn’t provide a built-in way to use ResizeObserver, but we can easily integrate it using a directive or a service.
Method 1: Creating a ResizeObserver Directive
A reusable directive allows us to observe element resizes anywhere in the app.
Step 1: Create the Directive
<button data-code="import { Directive, ElementRef, OnDestroy, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[appResizeObserver]'
})
export class ResizeObserverDirective implements OnDestroy {
private observer: ResizeObserver;
@Output() resize = new EventEmitter();
constructor(private el: ElementRef) {
this.observer = new ResizeObserver((entries) => {
for (const entry of entries) {
this.resize.emit(entry.contentRect);
}
});
this.observer.observe(this.el.nativeElement);
}
ngOnDestroy() {
this.observer.unobserve(this.el.nativeElement);
this.observer.disconnect();
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
import { Directive, ElementRef, OnDestroy, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[appResizeObserver]'
})
export class ResizeObserverDirective implements OnDestroy {
private observer: ResizeObserver;
@Output() resize = new EventEmitter<DOMRectReadOnly>();
constructor(private el: ElementRef) {
this.observer = new ResizeObserver((entries) => {
for (const entry of entries) {
this.resize.emit(entry.contentRect);
}
});
this.observer.observe(this.el.nativeElement);
}
ngOnDestroy() {
this.observer.unobserve(this.el.nativeElement);
this.observer.disconnect();
}
}
import { Directive, ElementRef, OnDestroy, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[appResizeObserver]'
})
export class ResizeObserverDirective implements OnDestroy {
private observer: ResizeObserver;
@Output() resize = new EventEmitter<DOMRectReadOnly>();
constructor(private el: ElementRef) {
this.observer = new ResizeObserver((entries) => {
for (const entry of entries) {
this.resize.emit(entry.contentRect);
}
});
this.observer.observe(this.el.nativeElement);
}
ngOnDestroy() {
this.observer.unobserve(this.el.nativeElement);
this.observer.disconnect();
}
}
Step 2: Use the Directive in a Component
<button data-code="Resize me!
onResize(rect: DOMRectReadOnly) {
console.log('New size:', rect.width, rect.height);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
<div appResizeObserver (resize)="onResize($event)">Resize me!</div>
onResize(rect: DOMRectReadOnly) {
console.log('New size:', rect.width, rect.height);
}
<div appResizeObserver (resize)="onResize($event)">Resize me!</div>
onResize(rect: DOMRectReadOnly) {
console.log('New size:', rect.width, rect.height);
}
Method 2: Using a ResizeObserver Service
For a more centralized approach, we can create a service.
Step 1: Create the Service
{
entries.forEach(entry => {
const element = entry.target as HTMLElement;
element.dispatchEvent(new CustomEvent('elementResized', {
detail: entry.contentRect
}));
});
});
}
observe(element: HTMLElement) {
this.observer.observe(element);
}
unobserve(element: HTMLElement) {
this.observer.unobserve(element);
}
ngOnDestroy() {
this.observer.disconnect();
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
import { Injectable, OnDestroy } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ResizeObserverService implements OnDestroy {
private observer: ResizeObserver;
constructor() {
this.observer = new ResizeObserver((entries) => {
entries.forEach(entry => {
const element = entry.target as HTMLElement;
element.dispatchEvent(new CustomEvent('elementResized', {
detail: entry.contentRect
}));
});
});
}
observe(element: HTMLElement) {
this.observer.observe(element);
}
unobserve(element: HTMLElement) {
this.observer.unobserve(element);
}
ngOnDestroy() {
this.observer.disconnect();
}
}
import { Injectable, OnDestroy } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ResizeObserverService implements OnDestroy {
private observer: ResizeObserver;
constructor() {
this.observer = new ResizeObserver((entries) => {
entries.forEach(entry => {
const element = entry.target as HTMLElement;
element.dispatchEvent(new CustomEvent('elementResized', {
detail: entry.contentRect
}));
});
});
}
observe(element: HTMLElement) {
this.observer.observe(element);
}
unobserve(element: HTMLElement) {
this.observer.unobserve(element);
}
ngOnDestroy() {
this.observer.disconnect();
}
}
Step 2: Use the Service in a Component
<button data-code="import { Component, ElementRef, OnDestroy, AfterViewInit } from '@angular/core';
import { ResizeObserverService } from './resize-observer.service';
@Component({
selector: 'app-example',
template: `Watch me resize!`
})
export class ExampleComponent implements AfterViewInit, OnDestroy {
constructor(
private el: ElementRef,
private resizeService: ResizeObserverService
) {}
ngAfterViewInit() {
const div = this.el.nativeElement.querySelector('div');
this.resizeService.observe(div);
div.addEventListener('elementResized', (event: CustomEvent) => {
console.log('Resized:', event.detail);
});
}
ngOnDestroy() {
const div = this.el.nativeElement.querySelector('div');
this.resizeService.unobserve(div);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
import { Component, ElementRef, OnDestroy, AfterViewInit } from '@angular/core';
import { ResizeObserverService } from './resize-observer.service';
@Component({
selector: 'app-example',
template: `<div #resizableDiv>Watch me resize!</div>`
})
export class ExampleComponent implements AfterViewInit, OnDestroy {
constructor(
private el: ElementRef,
private resizeService: ResizeObserverService
) {}
ngAfterViewInit() {
const div = this.el.nativeElement.querySelector('div');
this.resizeService.observe(div);
div.addEventListener('elementResized', (event: CustomEvent) => {
console.log('Resized:', event.detail);
});
}
ngOnDestroy() {
const div = this.el.nativeElement.querySelector('div');
this.resizeService.unobserve(div);
}
}
import { Component, ElementRef, OnDestroy, AfterViewInit } from '@angular/core';
import { ResizeObserverService } from './resize-observer.service';
@Component({
selector: 'app-example',
template: `<div #resizableDiv>Watch me resize!</div>`
})
export class ExampleComponent implements AfterViewInit, OnDestroy {
constructor(
private el: ElementRef,
private resizeService: ResizeObserverService
) {}
ngAfterViewInit() {
const div = this.el.nativeElement.querySelector('div');
this.resizeService.observe(div);
div.addEventListener('elementResized', (event: CustomEvent) => {
console.log('Resized:', event.detail);
});
}
ngOnDestroy() {
const div = this.el.nativeElement.querySelector('div');
this.resizeService.unobserve(div);
}
}
Browser Compatibility
ResizeObserver is supported in all modern browsers, but for older ones (like IE), you may need a polyfill:
npm install resize-observer-polyfill
npm install resize-observer-polyfill
Then, import it in polyfills.ts:
import 'resize-observer-polyfill';
import 'resize-observer-polyfill';
Performance Considerations
- Unobserve elements when not needed to avoid memory leaks.
- Debounce or throttle resize events if handling heavy computations.
Conclusion
ResizeObserver is a powerful API for tracking element size changes in Angular applications. Whether using a directive or a service, integrating it is straightforward and improves responsiveness.
Have you used ResizeObserver in your projects? Share your experiences in the comments!
📌 Stay Updated
Follow me for more design tips and tools! ✨
🐙 GitHub: Follow me for more web development resources.
🔗 LinkedIn: Connect with me for tips and tricks in coding.
✍️ Medium: Follow me for in-depth articles on web development.
📬 Substack: Dive into my newsletter for exclusive insights and updates:

