26

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!

14 Answers 14

20

Installing this node package

npm i -D @types/resize-observer-browser

solved the issue in Angular 10 project.

Sign up to request clarification or add additional context in comments.

2 Comments

I also had to add this snippet "types": ["resize-observer-browser"] to my TSConfig file for this solution to work (or add this type to the array if it already exists)
I had to add it to the TSConfig too, but then it worked in Angular 11 like a charm.
20

I suggest using resize-observer-polyfill it has types (in d.ts file) and if the browser support Resize Observer it just uses native implementation, but it has larger support because it uses Mutation Observer as a fallback that has a much bigger support.

So just use:

import ResizeObserver from 'resize-observer-polyfill';

Browser supports to compare:

as you can see Mutation Observer even work in IE 11.

1 Comment

so true. Now, resize-observer-polyfill has full TS support and works fine with Angular, for Chrome, Safari, Mozilla, and even IE.
19

I had the same problem because I of the empty "types" array in my tsconfig file. Solved by adding "resize-observer-browser" to the types array:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "typeRoots": ["node_modules/@types"],
    "types": ["resize-observer-browser"],
  }
}

2 Comments

this doesn't work for me. I literally banged my head for like 2 hours just to make it work. Though, as per current releases, simply importing ResizeObserver in your component works, import ResizeObserver from 'resize-observer-polyfill';
@saberprashant this is exact my answer, but without the code you need to use, since it's obvious how to use javascript library in TypeScript. Added it just now.
8

Install @types/resize-observer-browser not working on Angular 11. I ended up doing like this:

const observer = new (window as any).ResizeObserver...

2 Comments

I had this issue pop up for me in a Vue3 project. This did the trick.
Unfortunately, doesn't work!
6

Install npm i -D @types/resize-observer-browser

Add to tsconfig "types": ["resize-observer-browser"]

1 Comment

Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made
3

Just add the @ts-ignore flag. This will make Typescript happy again:

// @ts-ignore
const obs = new ResizeObserver(e => {
    // ...
});

1 Comment

I don not recommend ignoring TypeScript rules (except on edge cases).
1

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();
}

3 Comments

Thanks for this response! I had actually tried this originally, but the resize event did not detect the clientWidth property changes. I'm not sure there is a JS event for detecting changes to DOM properties?
Thanks! I've got the ResizeObserver doing the job now. Sorry you're not seeing my upvote ... I've only got 1 rep so it won't show mine yet haha.
Hey @JuanDelaCruz! Before some of the suggestions below were posted, I used 'resize-observer' from NPM import {ResizeObserver} from 'resize-observer'; and then in code: import {ResizeObserver} from 'resize-observer'; ``` // Observe this.myObserver = new ResizeObserver(entries => { // Do something }); this.myObserver.observe(this.parent); ``` Sorry for the comment format on this ... lemme know if you need more info!
1

I had the same issue in React that only happened for me in a specific iOs version (13.3), as @saberprashant mentioned, try to import it with import ResizeObserver from 'resize-observer-polyfill'; even if your IDE doesn't recommend that import.

Comments

1

I can't find a way to import @types/resize-observer-browser into my Angular 11 application. My workaround is to use declare:

    import { Component, ElementRef, OnInit, OnDestroy } from "@angular/core";
    
    declare var ResizeObserver;
    
    @Component({
      selector: "my-app"
    })
    export class AppComponent implements OnInit, OnDestroy {
      observer;
    
      constructor(private host: ElementRef) {}
    
      ngOnInit() {
        this.observer = new ResizeObserver(entries => {
           // handle resize 
        });
        this.observer.observe(this.host.nativeElement);
      }
    
      ngOnDestroy() {
        this.observer.unobserve(this.host.nativeElement);
      }
    }

Comments

1

Based on the typescript issue discussion, newer version of typescript can solve the issue.

If upgrading typescript is out of your control (like me, we are running an Angular 9 application, that only support typescript version from 3.6 to 3.8) const observer = new (window as any).ResizeObserver(...) solved the issue temporarily.

1 Comment

Unfortunately, doesn't work!
1

I have encountered this problem with Angular 11 and none of the solutions suggested felt suitable:

  1. Any workarounds like
    const observer = new (window as any).ResizeObserver
    or
    declare var ResizeObserver;
    Look like a hack rather than the solution

  2. Installing polyfill
    import ResizeObserver from 'resize-observer-polyfill';
    Was not an option because I wanted to use native observer rather than polyfill

What helper was installing type definitions

npm i -D @types/resize-observer-browser 

And adding them to tsconfig.json

But rather than adding to types (which does not help)
{"compilerOptions": { "types": ["resize-observer-browser"]}

I've added the definition file itself

"files": ["node_modules/@types/resize-observer-browser/index.d.ts"]

Works like a charm

Comments

0

I was unable to fix this with any of the provided answers in this thread for a lib in my Nx workspace.

I also installed the dep: @types/resize-observer-browser

Then where I use the ResizeObserver, I had to add the following to the top of my file:

/// <reference types="resize-observer-browser" />

Annoying as hell, but beats new (window as any).ResizeObserver(), atleast in my opinion.

Comments

0

using the ResizeObserver like below

let observer = new (ResizeObserver as any)((entries) => {
      let currentWidth = entries[0].contentRect.width;
    });
    observer.observe(document.getElementById('someId'));
  }

working for me

Comments

-3

Adding import '@types/resize-observer-browser'; fixed it for me

1 Comment

This didn't work, Angular told me it couldn't resolve the types file even though it was in the correct location.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.