[Fixed] Finding ResizeObserver with Typescript in Angular 9

Issue

I am trying to implement a ResizeObserver in an Angular app:

const obs = new ResizeObserver(e => {
      // ...
});

… and am met with the TS error:

TS2304: Cannot find name 'ResizeObserver'.

I’ve tried to update my type definition with:

@types/resize-observer-browser

… however my issue persists. Is there an advisable solution or common workaround, or would it be better to use an NPM package like ‘resize-observer’ to keep moving forward?

Happy to include more info if needed.

Tks!

Solution

I’ve never used ResizeObserver, however I do use fromEvent from RxJS with the resize event and it’s working fine. Here is the code for it.

import { fromEvent, Observable, Subscription } from "rxjs";

resizeObservable$: Observable<Event>;
resizeSubscription$: Subscription;

ngOnInit() {
  this.resizeObservable$ = fromEvent(element, 'resize')
  this.resizeSubscription$ = this.resizeObservable$.subscribe(evt => {
     // do whatever you waant
  })
}

ngOnDestroy() {
  this.resizeSubscription$.unsubscribe();
}

Leave a Reply

(*) Required, Your email will not be published