Angular - tracking the window scroll event to target a specific scrollbar on a page with multiple scrollbars

I am facing difficulty in accessing a specific scrollbar from a component in my web page. The page contains multiple scrollbars, and I need to target and modify the position of a particular scrollbar (scrollTop).

I have tried implementing the following code in the child component to display a single scrollbar in a div (refer to the screenshot below):

@HostListener('window:scroll', ['$event']) onScrollEvent($event: any) {
    console.log(window.pageYOffset);
}

However, I noticed that this event is only triggered when I adjust the scrollbar in the parent component.

Link to Screenshot

Answer №1

Each individual element has its own scroll event to trigger and respond to. When you listen to the window scroll event, you are specifically listening to the window's scroll event and not that of a particular element.

To access the scrollTop of an element in Angular, you can obtain the DOM element by referencing it using the @ViewChild() decorator like this:

First, you need to assign a template variable to the element to give it an Angular identifier

<div #scrollElement style="overflow-y=scroll"></div>

In your component, you can refer to your scroll element like this:

@ViewChild('scrollElement', {use: ElementRef}) private childEl: ElementRef;

Then, you can access and modify the scrollTop property in your method like so:

setScrollTop() {
  this.childEl.navtiveElement.scrollTop = 50;
}

Here is a Stackblitz showcasing an example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

Retrieving data from a nested JSON array using AngularJS

I am struggling to navigate the intricate nested tree view of child items within a JSON array. I have been grappling with this challenge for days, trying to figure out how to access multiple children from the complex JSON structure. Can someone provide g ...

When attempting to open a form in edit mode, data binding fails to work across multiple form controls

When clicking on the edit button, data is loaded into the form using [(ng-model)], however, it seems to be working correctly only for some fields and not all fields. The data is displayed in only a few fields despite receiving data for all fields. Below is ...

Unable to apply styling to table cells that are dynamically added using JQuery within an Angular

Currently working on setting up a form using Angular. Within the hotel.view.html file, there is a table that looks like this: <table id="rooms"> <tr> <td>Room Type</td><td>Beds</td><td>Q.ty</td ...

What is the best way to pass a string array in a post request using HttpClient in Angular 14?

Trying to send a string array using HttpClient's post method to my backend. getAnnouncementsByIds(ids: string[]): Observable<Announcement[]> { return this.http.post<Announcement[]>(`${environment.serverUrl}${this.urlGetAnnouncementsByIds ...

Creating autorest client based on various OpenAPI versions

I'm currently exploring options for creating a Typescript client from our .NET API. After researching various tools, I decided to go with Autorest, as it is Node-based and fits my skillset. While I am aware of Swashbuckle, my knowledge leans more towa ...

Create a series of buttons in Angular 2 that are linked to components with a click event

I am facing an issue with a component that generates a list of buttons, where I want to connect the click event to show a child component. The problem is that my current implementation using a local variable causes all buttons to display the last child com ...

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

Angular 4 Issue: Child Routing Dysfunction

I'm encountering an issue with the child routing in Angular 4. The parent routing is functioning correctly, but when I hover over "Create New Account," it remains on the Account page instead of redirecting to localhost:4200/account/create-account. The ...

Guide on integrating a dynamic element within another element in Angular

Imagine a scenario where we have the following html structure <div [innerHTML]="contentFromAPI | safeHTML"></div> The content retrieved from the api contains multiple HTML elements, resulting in a structure like this: <div> &l ...

Experiencing an Issue with NGINX Loading Vue 3 Vite SPA as a Blank White Page

I currently have the following NGINX configuration set up: events { worker_connections 1024; } http { server { listen 80; server_name localhost; location / { root C:/test; index index.html; ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

Function that wraps JSX elements with the ability to infer types through generics

At the moment, this function is functioning properly function wrapElement(elem: JSX.Element) { return ({ ...props }) => React.cloneElement(elem, { ...props }) } I've been using it in this way to benefit from intelliSense for tailwind classes con ...

Transform a nested AngularJS service into an Angular Observable service

Currently, I am working on migrating AngularJS(pre 1.5) services that use nested calls to a project being rebuilt in Angular(11). The challenge I'm facing is how to rewrite these services using RXJS. I have been searching for resources or detailed ex ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

Creating a Prisma schema with a complex nested structure and incorporating an array of strings for a specific property

I'm trying to create a detailed Prisma schema for a product database that includes nested properties and an array of strings for image content. The structure I'm aiming for looks like this: interface Product { id: number; name: string; ...

Resolving search box setup problem in PrimeNG dataView

I am working on integrating p-dataView with Angular 5 but encountering an error Cannot read property 'split' of undefined at DataView.filter Despite checking the documentation, I have been unable to find a solution to this issue. It seems lik ...

Following an Angular update, the npm installation process encounters issues due to conflicts related to peer dependencies

I am facing challenges with updating my Angular version. When I try to use the command ng update, the output I receive is as follows: Name Version Command to update ------------------------------ ...

What is the best way to transfer two distinct states from my ngrx effect to my service function?

I am encountering a dilemma with my effects function, where I am attempting to pass data from a dispatched action and a separate selector to a service function. However, I am finding myself confused by the RXJS syntax and suspect that I may not be mapping ...