2

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?

Steve
  • 14,401
  • 35
  • 125
  • 230
  • It would be alot easier to show you if you gave the angular 6 component you're working on as well. Simply put, you bind the class you want to be optional to a function. `
    `. To listen for scroll events, see [this](https://stackoverflow.com/questions/36468318/tracking-scroll-position-and-notifying-other-components-about-it)
    – fredrik May 31 '18 at 17:40
  • Possible duplicate of [Tracking scroll position and notifying other components about it](https://stackoverflow.com/questions/36468318/tracking-scroll-position-and-notifying-other-components-about-it) – fredrik May 31 '18 at 17:40

1 Answers1

1

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);
    }
  }
}
MichaelSolati
  • 2,847
  • 1
  • 17
  • 29