简体   繁体   中英

TypeError: Cannot read properties of null (reading 'scrollHeight') | Angular 11

I really hope that some of you could help me to resolve this head-scratcher. I need to have the scrollHeight of the page, but I get just 1/3 of that.

setSize() {
    let DOMScrollable = this.elementRef.nativeElement.querySelector("div[data-scroll]");
    document.body.style.height = DOMScrollable.scrollHeight + "px";
}

console.log(this.dataScroll.nativeElement.scrollHeight)
// 1177

Analyzing the DOMSrollable.nativeElent , the real size of scrollHeight is 4587. So, using the function above I can't go down, because the scroll stops on 1177px.

Here's an abstraction of (my Typescript/Angular 12) what I'm dealing with. This is the HTML (On my page I have 8 images)

<main main>
  <div data-scroll #dataScroll>
        <div class="page">
            <header>
                    <h1>Oceans</h1>
                    <img src="../assets/images/header.jpg" alt="">
            </header>
            <div class="grid">
                <a href="#" class="item item_v">
                    <div class="item__image">
                            <img src="../assets/images/1.jpg" alt="">
                            <div class="item__meta">December 23, 2020</div>
                    </div>

                    <h2 class="item__title">Octopus punches fish in the head (just because it can)</h2>
                    <p>Octopuses sometimes partner with fish to hunt, but the partnership comes with risks (for the fish, that is).</p>
                </a>
            </div>
         </div>
  </div>
</main>

Thanks in advance

Try using getBoundingClientRect instead of scrollHeight . eg:

setSize() {
    let DOMScrollable = this.elementRef.nativeElement.querySelector("div[data-scroll]");
    const rect = DOMScrollable.getBoundingClientRect();
    document.body.style.height = rect.height + "px";
}

console.log(rect.height)
// 4587

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM