Angular class change on scroll

HTML

<ion-app>
  <ion-content>
    <div #scrolledToElement class="second-block" [ngClass]="flag ? 'red' : 'green' "></div>
  </ion-content>
</ion-app>

CSS

.second-block {
  margin-bottom: 500px;
  height: 250px;
  width: 100%;
}
.red {
  background: red;
}
.green {
  background: green;
}

TS

import { Component, VERSION, HostListener, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Ionic 6.2 Angular ' + VERSION.major;

  constructor() {}

  flag = false;
  @ViewChild("scrolledToElement", { static: false })
  scrolledToElement: ElementRef;
  @HostListener("window:scroll", ["$event"])
  onScroll(event) {
    if (window.scrollY > this.scrolledToElement.nativeElement.offsetTop) {
      this.flag = true;
      console.log("flag", this.flag);
    }
    else
    {
      this.flag = false;
    }
  }
}

How to change the class on scroll? I am looking for a solution for the most recent Angular version stackblitz : https://stackblitz.com/edit/ionic6-angular13-wsjtit?file=src%2Fapp%2Fapp.component.html

Any suggestions, please?

Functional URL : https://stackblitz.com/edit/angular-ivy-xhb4yw?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.css,src%2Findex.html,src%2Fapp%2Fhello.component.ts,src%2Fapp%2Fapp.module.ts

Answer №1

@HostListener('window:scroll', ['$event']) is functioning well in the web browser. However, when working with Ionic, it is recommended to utilize the custom events specified in the ion-content documentation.

  <ion-content [scrollEvents]="true"
  (ionScrollStart)="logScrollStart($event)"
       (ionScroll)="logScrolling($event)" 
       (ionScrollEnd)="logScrollEnd($event)">
       
       
       
  </ion-content>

Implement the above methods in your app.component.ts file. You can establish your class change logic in the logScrolling method. Instead of using window.scrollY, utilize event.detail.scrollTop from the event provided by ionScroll.

logScrollStart(event) {
    console.log("logScrollStart : When Scroll Starts", event);
 }

 logScrolling(event) {
    console.log("logScrolling : When Scrolling", window.scrollY);
    console.log("Offset", this.scrolledToElement.nativeElement.offsetTop);
    if (event.detail.scrollTop > this.scrolledToElement.nativeElement.offsetTop) {
      this.flag = true;
      console.log('flag', this.flag);
    } else {
      this.flag = false;
    }
 }

 logScrollEnd(event) {
    console.log("logScrollEnd : When Scroll Ends", event);
 }

For reference, here is the forked stackblitz repository.

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

What is the process for linking HTML files to a Node.js/Express server backend?

As I delve into my school project, I have encountered a hurdle that has left me searching for a suitable solution. The project involves creating multiple HTML pages, styling them with CSS, adding functionality using JavaScript, and ultimately integrating b ...

The animations in fontawesome 6.2 are completely ineffective

I've been struggling to make a spinner icon spin on my webpage. I made sure to download the latest version of font awesome and created a simple HTML file to troubleshoot the issue. Take a look at the HTML code below: <!doctype html> <html la ...

Placeholder variable not specified in radio buttons

I am currently facing challenges applying validations to radio buttons in Angular. Normally, I create a #templateRefVariable on the input for other input types, which allows me to access the NgControl and use properties like touched. My goal is to set the ...

The Angular material datepicker fails to organize items in a horizontal row

My web application features an Angular Material datepicker, however, I am facing an issue where not all elements are showing up in a row. The view is as follows: Datepicker To prevent any custom CSS from impacting the view, I have removed all customized ...

How can we eliminate all elements from jQuery except for the first and second elements?

HTML <div class="geo_select"> <h3>header 3</h3> in Above HTML code i want to remove all element except <h3> and default content<div> inside the <div class='geo_select'> in jquery.. How to remove all ...

Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services. To address this problem, I modified ...

GZIP compression causes a total page layout malfunction

Thank you for taking the time to visit. I've been attempting to tackle this issue on my own, but it seems to be a bit overwhelming for me once again. THE SCENARIO... I have my website live on a shared hosting platform. As I delved into compressing my ...

Whenever I attempt to launch the application on my device, an error message stating "plugin_Not_Installed Exception" occurs

I encountered a plugin_Not_Installed Exception when running the app on my device. Here are the details of my Ionic setup: Ionic: Ionic CLI : 5.4.16 Ionic Framework : @ionic/angular 6.2.2 @angular-devkit/build-angular : 1 ...

Searching for mobile WiFi preferences through a web browserHere are the steps to

Is there a method to access mobile connectivity settings through a website? I am interested in determining the connection type (3G\4G\WiFi) and if it is WiFi, identifying the security method being used. Is this achievable? If so, how? Edit: If ...

Utilizing local images in Angular with route navigation

I am new to Angular and currently learning about routes, but I have encountered a problem. In my application, I have defined the following routes. However, when trying to link to an image in the assets folder, I receive an error stating that there is no r ...

What could be causing the availability of a response in a service, but showing as undefined in the component?

Currently, I am facing a problem with my service and component setup. While the service can successfully read the response as a JSON object, the component is returning res: undefined. service: constructor( private http: Http, private fbuilder: Fo ...

A Typescript interface designed for a higher-order function that returns another function

I am working with a StoryOptions object that includes a property called actionFn. This property, when invoked, will return a function utilizing function currying. The actionFn function must accept an object of type ActionBundle</code and should return ...

Angular 2 - Component Loading Screen

I'm looking for a solution for my loading component that shows a spinner and retrieves a remote configuration file necessary for the app to work. Is there a way to have all routes pass through the loading component first to ensure the config data is l ...

Tips for transferring variable amounts using PaymentIntent

I have integrated a static price into my Stripe test project in Next.js, but I now want the payment amount to be dynamic based on user input. I am seeking guidance on how to properly pass this data in the paymentIntent function: //Within Checkout.js try { ...

Does anyone know of a tool that allows you to save HTML as a standalone page?

Looking for a solution to easily send standalone .html files with no external dependencies to clients on a regular basis. The original pages are built using node.js and express, and feature libraries like High Charts. Up until now, I have been manually pre ...

Tips for defining conditions within the style attribute in JSP

Below is the code that I attempted: <div style="width:85%;"> <input class="formbutt" value="AddNew" title="AddNew" type="button" style="{(${projectEnvironmentBean.divStyle}=='dipslay:none') ? 'display:block' :'display: ...

Issue with TypeScript: Assigning type 'type' to 'IntrinsicAttributes & type & { children?: ReactNode; }' is not allowed. What is the solution?

I'm currently working on a small home project to enhance my skills in TypeScript. Everything was running smoothly with retrieving data from the server and displaying posts without any errors. However, when I decided to separate the code with the map i ...

Creating a String Array and linking it to an Input Field

I'm currently working on a code that involves mapping through an array of strings using observables. My objective is to display the value from this array inside an input field. However, despite being able to view the array in the console, I encountere ...

Applying styled numbering to elements using nth-child selector in

I have a div with multiple p tags inside. My goal is to assign them numbers using CSS. The number of p tags may vary. By using the :nth-child() selector and the ::before pseudo-element, I can achieve something like this: div p:first-child::before { ...

The issue persists with Angular's overflow hidden not functioning properly, and similarly, the show password button is

I created a login page using Angular Material, but I'm facing some issues. The problem is that when I set the style overflow: hidden, the show password button stops working. Additionally, if I click the button twice, the webpage refreshes, which shoul ...