Search code examples
cssangular8angular11

How to change the sticky header background color on scroll in angular 11


Tried to change the background color on scroll to the sticky header but not working. How to do it? when I scroll to the bottom of the body I need to change the header background color. How to do it?

app.component.html

<div class="header sticky">
</div>

app.component.css

 .sticky {
 position: -webkit-sticky;
 position: sticky;
 top: 0px;
 }

Demo: https://stackblitz.com/edit/sticky-header-hyibz9?file=app%2Fheader%2Fheader.component.css


Solution

  • You can use ngClass for this and HostListener to check if user scrolled at the buttom

    html

    <div class="header sticky" [ngClass]="isBottom ? 'bottom' : 'top'">
    </div>
    

    ts

    import { Component, OnInit, HostListener } from '@angular/core';
    
    @Component({
      selector: 'app-header',
      templateUrl: './header.component.html',
      styleUrls: ['./header.component.css']
    })
    export class HeaderComponent implements OnInit {
      isBottom: boolean;
    
      constructor() {}
    
      ngOnInit() {}
    
      @HostListener('window:scroll', [])
      onScroll(): void {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
          this.isBottom = true;
        } else {
          this.isBottom = false;
        }
      }
    }
    

    css

    .sticky {
      position: -webkit-sticky;
      position: sticky;
      top: 0px;
    }
    
    .header {
      height: 50px;
    }
    
    .top {
      background-color: blue;
    }
    
    .bottom {
      background-color: yellow;
    }