Search code examples
angularangular-directive

Angular Directive to add class to component on scroll?


In my older AngularJS app, we made a directive to add and remove a class to an element based on scroll position:

(function () {
  'use strict';

  angular.module('pb.ds.components').directive('pbdsHeaderShadow', function ($window) {
    return {
      restrict: 'AE',
      link: function postLink (scope, element) {

        angular.element($window).on('scroll', function () {
          if (this.pageYOffset > 20) {
            element.addClass('shadow');
          } else {
            element.removeClass('shadow');
          }
        });
      }
    };
  });
})();

What's the Angular (6) way to create this same directive?


Solution

  • Throwing together a little stab in the dark...

    @Directive({
      selector: '[pbdsHeaderShadow]',
    })
    export class HeaderShadowDirective implements OnInit, OnDestroy {
      @HostBinding('class.shadow') shadow: boolean;
    
      constructor() { }
    
      ngOnInit() {
        if (typeof window !== undefined) {
          window.addEventListener('scroll', () => this._checkScroll());
        }
    
      }
    
      ngOnDestroy() {
        if (typeof window !== undefined) {
          window.removeEventListener('scroll', () => this._checkScroll());
        }
      }
    
      private _checkScroll() {
        if (typeof window !== undefined) {
          this.shadow = (window.pageYOffset > 20);
        }
      }
    }