2

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;
}
James Z
  • 12,209
  • 10
  • 24
  • 44
surjendu_dey
  • 578
  • 2
  • 11
  • 28
  • This question is very similar to [this other question](https://stackoverflow.com/q/59910252/1009922), posted two hours ago. – ConnorsFan Jan 25 '20 at 17:08
  • can I get a solution how to do it? – surjendu_dey Jan 25 '20 at 17:10
  • Does this answer your question? [How to properly handle Navbar color change on Scroll in Angular?](https://stackoverflow.com/questions/57904628/how-to-properly-handle-navbar-color-change-on-scroll-in-angular) – Viral Feb 01 '20 at 12:10

1 Answers1

4

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