Angular 6 make Header Sticky on Scroll

This article will help you to make header component sticky on scrolling on another component.

Let's consider situation where you have an Angular 6 application with 2 components other than root component

  • Header component
  • Home component







In order to make the Header component sticky while scrolling on Home Component what we need to do is add a new class (some class name) , here in my case it is sticky

Css class
.sticky {
    background: #fff;
    box-shadow: 0 3px 12px 0 rgba(0,0,0,.08);
    position: fixed;
    top: 0;
    height: 120px;
    width: 100%;
}



First we need to give an id attribute to the header component so we can identify which element we to add the class sticky . Here i am giving it an id navbar



header.component.html
<header class="animated fadeInDown" id="navbar">  
 <!-- other html code -->
</header>  

Now go to the Home Component and write a function to handle the scroll event



home.component.ts
import { Component, OnInit, HostListener, Inject } from '@angular/core';  
import { trigger, state, transition, style, animate } from '@angular/animations';  
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  animations:[ 
    trigger('fade',
    [ 
      state('void', style({ opacity : 0})),
      transition(':enter',[ animate(300)]),
      transition(':leave',[ animate(500)]),
    ]
)]
})
export class HomeComponent implements OnInit {


  constructor(@Inject(DOCUMENT) document) { }

  ngOnInit() {  }

  @HostListener('window:scroll', ['$event'])
  onWindowScroll(e) {
     if (window.pageYOffset > 550) {
       let element = document.getElementById('navbar');
       element.classList.add('sticky');
     } else {
      let element = document.getElementById('navbar');
        element.classList.remove('sticky'); 
     }
  }


}



Next we need to add the scroll event in the Home Component to trigger the onWindowScroll function on scroll event



home.component.html
<section class="web_homePage" (scroll)="onWindowScroll($event);">  
   <!-- rest of the html code goes here -->
</section>  

Now you can see that a new class is added / removed to the element with id navbar on scrolling on the Home component