首页 > 解决方案 > Angular 指令在滚动时向组件添加类?

问题描述

在我的旧 AngularJS 应用程序中,我们创建了一个指令来根据滚动位置向元素添加和删除一个类:

(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');
          }
        });
      }
    };
  });
})();

创建相同指令的 Angular (6) 方法是什么?

标签: angularangular-directive

解决方案


在黑暗中拼凑出一点点刺...

@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);
    }
  }
}

推荐阅读