surjendu_dey
surjendu_dey

Reputation: 588

Angular [ngClass] should change navbar color on scrolling event

I'm pretty much new in angular. I'm trying to achieve a functionality where the navbar will change from transparent to dark upon scrolling the page. But in my application the navbar remains transparent even after scrolling. How to achieve that?

The code which I tried:

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

Upvotes: 2

Views: 1860

Answers (1)

Mugunthan C
Mugunthan C

Reputation: 41

Here is the sample solution for your question jsfiddle

Html

<nav class="navbar navbar-expand-lg fixed-top navbar-transparent" [ngClass]="{'navbar-inverse': isScrolled}">

angular component.ts

Declare a variable(isScrolled) to handle add/remove a class to the nav element.

isScrolled = false;

@HostListener("window:scroll")
scrollEvent() {
    window.pageYOffset >= 80 ? (this.isScrolled = true) : (this.isScrolled = false);
}

Upvotes: 4

Related Questions