问题
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:
- $event is not defined in scope of HTML; some explanation how it works
- Such as return type is
: void
- you are not returningboolean
.
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