【问题标题】:Angular Directive to add class to component on scroll?Angular 指令在滚动时向组件添加类?
【发布时间】:2018-11-10 19:01:45
【问题描述】:

在我的旧 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) 方法是什么?

【问题讨论】:

  • 如果您也提供了您正在处理的 angular 6 组件,向您展示会容易得多。简而言之,您将希望成为可选的类绑定到一个函数。 <div [class.somthing]="checkSomething()"></div>。要监听滚动事件,请参阅this

标签: angular angular-directive


【解决方案1】:

在黑暗中拼凑出一个小刺......

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

【讨论】:

  • 不错。这比我们开始做的要简单得多。谢谢。
  • 希望这确实有效,?。如果它确实让我知道!
  • 像魅力一样工作..!!谢谢@迈克尔索拉蒂
猜你喜欢
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
相关资源
最近更新 更多