Jérémie Czk
Jérémie Czk

Reputation: 151

Angular Property 'offsetWidth' does not exist on type 'Element'

new to angular, I am trying to use ScrollTrigger for horizontal scroll.

It work, but when I serve or build I got the error : Property 'offsetWidth' does not exist on type 'Element'.

This is the code for the gsap :

gsap.to(sections, {
  xPercent: -100 * (sections.length - 1),
  ease: "none",
  scrollTrigger: {
    trigger: ".panel-container",
    pin: true,
    scrub: 1,
    snap: 1 / (sections.length - 1),
    end: () => "+=" + document.querySelector(".panel-container").offsetWidth
  }
});

Even if I get the error it work, when I console log the "document.query.." I got the good width of the element.

But the error prevent me to ng build. I already did the cast thing, first with :

let myElem = document.querySelector(".panel-container").offsetWidth as HTMLElement;

Or with before but this don't work, I have the line with red underline with error message : Conversion of type 'string' to type 'HTMLElement' may be a mistake because neither type sufficiently overlaps with the other.

My angular project is 10.0.5.

Tried the solution in reply :

(document.querySelector(".panel-container") as HTMLElement).offsetWidth;

But got this error on red underline, but nothin in console when I ng serve.

Conversion of type 'Element' to type 'HTMLElement' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'Element' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 105 more.ts(2352)

Upvotes: 15

Views: 30867

Answers (2)

atom217
atom217

Reputation: 987

The result can be null, so if you have strictNullChecks enabled you need to perform a null check first:

if (element !== null) { ... }

Upvotes: 0

Jago
Jago

Reputation: 2945

Try typing the expected output from querySelector.

That is:

document.querySelector<HTMLElement>(".panel-container").offsetWidth

Upvotes: 37

Related Questions