Home > Back-end >  Change styles in all Divs on Scroll Event | Angular
Change styles in all Divs on Scroll Event | Angular

Time:10-01

I want to change the padding of all the tags with same id on scroll. But only first tag is changing. Rest of the tags are not changing.

My view:

<a #nav> Home </a>
<a #nav> About </a>
<a #nav> Contact </a>

Only Home padding is changing. TS:

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

declare const window: any;
@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})

export class NavComponent implements OnInit {

  @ViewChild('nav')
  elementRef!: ElementRef;

  constructor() {}

  ngOnInit(): void {
  }



  //Sticky Menu
  @HostListener("window:scroll", ['$event'])
  onWindowScroll(event: Event){ 
    const number = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
    
    event.preventDefault();
    if (number > 300) {
      this.elementRef.nativeElement.style.setProperty('padding', '19px 0px');
      console.log(this.elementRef);
    } else {
      this.elementRef.nativeElement.style.setProperty('padding', '39px 0px');
    }
  }
  

}

CodePudding user response:

ViewChild should be unique which will evaluate with the first element that holds it only.

What you are looking for is ViewChildren

import { Component, OnInit, HostListener, QueryList, ViewChildren, ElementRef } from '@angular/core';

declare const window: any;
@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})

export class NavComponent implements OnInit {

  @ViewChildren('nav') elementRefs: QueryList<ElementRef>

  constructor() {}

  ngOnInit(): void {
  }



  //Sticky Menu
  @HostListener("window:scroll", ['$event'])
  onWindowScroll(event: Event){ 
    const number = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
    
    event.preventDefault();
    this.elementRefs.forEach((element: ElementRef) => {
    if (number > 300) {
      element.nativeElement.style.setProperty('padding', '19px 0px');
      console.log(element);
    } else {
      element.nativeElement.style.setProperty('padding', '39px 0px');
    }
    })
  }
  

}

Then you can loop through and set your styles.

  • Related