How to add css class to a div with typescript in angular

When I scroll down, the class is not added on the div element.

 export class TestComponent {
  constructor(public el: ElementRef) {}

    @HostListener('window:scroll', [])
    checkScroll() {
      var line = this.el.nativeElement;

      for (var i = 0; i < line.length; i++) {
        var windowHeight = window.innerHeight;
        var elementTop = line[i].getBoundingClientRect().top;
        var elementVisible = 150;
        if (elementTop < windowHeight - elementVisible) {
          line[i].classList.add('active-line');
        } else {
          line[i].classList.remove('active-line');
        }
      }
      console.log('scrolling');
      console.log(line);
    }
}
<div class="mx-4 bd-highlight line"></div>

I want that when I scroll down to make this div from this <div class="mx-4 bd-highlight line"></div> to this <div class="mx-4 bd-highlight line active-line"></div>

  • Coudl you provide a working example? It will be very find out what the issue is just from the code. I would suspect that your if statement may be fault here and the code for adding a class is just not executed.

    – 

  • yeah, but I want to be more clear just in case nothing else

    – 

  • if the if statement may be fault why does it work on javascript? and how to execute that code?

    – 




  • just tell me one thing how many such divs are there, are you using *ngFor ??

    – 

Leave a Comment