angular - 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) 方法是什么?
解决方案
在黑暗中拼凑出一点点刺...
@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);
}
}
}
推荐阅读
- laravel - 雄辩,返回 null
- git - Git 在 master 上的作者姓名与其他分支不同
- powershell - Powershell函数参数正确使用
- r - 使用 tidyverse 重塑 data.frame 及其列名
- javascript - 从频道获取一系列消息
- php - Laravel 图片上传验证失败
- c# - 检索隐藏的文本块并替换其中两个之间的所有内容
- python - 不使用范围的 Python 中的高效迭代
- reactjs - 由 nginx 后面的 express 提供的 React Okta 身份验证
- python-3.x - GZIP python3 AttributeError:“模块”对象没有属性“压缩”