Search code examples
angularscrollng-class

How to add class on scroll in Angular


Just learning Angular again. Installed AngularCLI and am trying to add a class on scroll from what I had before using jquery. Do I need to use [ngClass] to check a variable with window location? I am trying to use @HostListener right now.

$(function () {
 $(document).scroll(function () {
   $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
 });
});

$(function() {
 $(document).scroll(function() {
  var x = $(this).scrollTop();
  if (x > 3300) {
    $nav.removeClass('scrolled');
  }
 });
});

Solution

  • You can do something like this-

    import { Component, HostListener, Inject } from '@angular/core';
    import { DOCUMENT } from '@angular/common';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    
      constructor(@Inject(DOCUMENT) private document: Document) { }
    
      @HostListener('window:scroll', [])
      onWindowScroll() {
        if (document.body.scrollTop > 20 ||     
        document.documentElement.scrollTop > 20) {
          document.getElementById('subTitle').classList.add('red');
          document.getElementById('paragraph').classList.add('green');
        }
      }
      name = 'Angular';
    }
    

    See live example here: https://stackblitz.com/edit/angular-changeclassonscroll