如何在 Angular 中添加滚动类

Ken*_*nzo 3 scroll ng-class angular

刚刚又学习了 Angular。安装了 AngularCLI 并尝试从使用 jquery 之前的滚动中添加一个类。我是否需要使用 [ngClass] 来检查具有窗口位置的变量?我现在正在尝试使用@HostListener。

$(function () {
 $(document).scroll(function () {
   $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
 });
});

$(function() {
 $(document).scroll(function() {
  var x = $(this).scrollTop();
  if (x > 3300) {
    $nav.removeClass('scrolled');
  }
 });
});
Run Code Online (Sandbox Code Playgroud)

Sho*_*fol 16

你可以做这样的事情——

import { Component, HostListener, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(@Inject(DOCUMENT) private document: Document) { }

  @HostListener('window:scroll', [])
  onWindowScroll() {
    if (document.body.scrollTop > 20 ||     
    document.documentElement.scrollTop > 20) {
      document.getElementById('subTitle').classList.add('red');
      document.getElementById('paragraph').classList.add('green');
    }
  }
  name = 'Angular';
}
Run Code Online (Sandbox Code Playgroud)

在此处查看现场示例:https : //stackblitz.com/edit/angular-changeclassonscroll


pis*_*ete 8

上面的解决方案是有效的,但我认为尽可能地利用框架更干净、更合适。

打字稿文件:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

    scrolled: boolean = false;

    @HostListener("window:scroll", [])
    onWindowScroll() {
        this.scrolled = window.scrollY > 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

网页:

<div [ngClass]="{ className: scrolled }"></div>
Run Code Online (Sandbox Code Playgroud)