Angular [ngClass] directive not working on scroll event

♀尐吖头ヾ 提交于 2020-02-03 01:30:12

问题


I'm using Angular 8 and bootstrap 4 to build a navbar which changes its color from transparent to dark when a certain amount to scroll happens. I'm using [ngClass] directive in order to achieve it. The function inside component.ts will return either true or false depending upon the scroll happened or not and ngClass will act accordingly. But I cannot unfortunately achieve it. Kindly take a look at my code below:

HTML

<nav class="navbar navbar-expand-lg fixed-top navbar-transparent" [ngClass]="{'navbar-inverse': scrollEvent($event)}">

angular component.ts

ngOnInit() {
        window.addEventListener('scroll', this.scrollEvent, true);
    }
scrollEvent = (event: any): void => {

      }

css

.navbar-inverse {
    background-color: #918d8d;
}

回答1:


  1. $event is not defined in scope of HTML; some explanation how it works
  2. Such as return type is : void - you are not returning boolean.

Approach to solving this would be setting the value(when needed) to something like navbarInversed and use it in the template

Don't use direct addEventListener - use HostListener or RxJS's fromEvent

This answer is a good example of what you need



来源:https://stackoverflow.com/questions/59910252/angular-ngclass-directive-not-working-on-scroll-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!