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?

2
  • 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. <div [class.somthing]="checkSomething()"></div>. To listen for scroll events, see this Commented May 31, 2018 at 17:40
  • Possible duplicate of Tracking scroll position and notifying other components about it Commented May 31, 2018 at 17:40

1 Answer 1

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);
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice. That's far simpler than what we were starting to do. Thanks.
Well hopefully that actually works, 😅. If it does let me know!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.