Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding ResizeObserver with Typescript in Angular 9

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!

like image 983
jared jessup Avatar asked Feb 17 '20 21:02

jared jessup


6 Answers

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"],
  }
}
like image 190
Mikhail Fursov Avatar answered Sep 28 '22 22:09

Mikhail Fursov


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:

  • Resize Observer
  • Mutation Observer

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

like image 40
jcubic Avatar answered Sep 28 '22 23:09

jcubic


Installing this node package

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

solved the issue in Angular 10 project.

like image 42
robert Avatar answered Sep 28 '22 21:09

robert


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

const observer = new (window as any).ResizeObserver...
like image 26
Duc Trung Mai Avatar answered Sep 28 '22 22:09

Duc Trung Mai


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

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

like image 40
Tommy Norgren Avatar answered Sep 28 '22 22:09

Tommy Norgren


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

// @ts-ignore
const obs = new ResizeObserver(e => {
    // ...
});
like image 20
Bartek Avatar answered Sep 28 '22 21:09

Bartek