Angular 8 scroll manipulation

Asked

Viewed 497 times

-2

I am developing a component in Angular version 8 and in the html part of the component I am using the following navbar: https://bootsnipp.com/snippets/kl8Q3 but when I try to embed javascript in my component I can’t implement it in typescript.

After doing research on how to "convert" js to typescrip I found obsolete examples that didn’t work. I have little knowledge in Angular and I have no idea how to proceed with the solution of this problem. Below is the code that I intend to use:

 $(document).ready(function() {
            $(".menu-icon").on("click", function() {
                  $("nav ul").toggleClass("showing");
            });
      });

      // Scrolling Effect

      $(window).on("scroll", function() {
            if($(window).scrollTop()) {
                  $('nav').addClass('black');
            }

            else {
                  $('nav').removeClass('black');
            }
      })
  • What error are you getting ? No need to install jquery type lib ? npm i -D @types/jquery

  • I get no error. This javascript code does not work in my angular application. You know where it should be placed?

  • You can try to put it on ngOnInit() of its navbar component.

1 answer

1

The solution I found was this

Typescript

import { Component, OnInit, HostListener, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  constructor() {

  }

  ngOnInit() {

  }

  @ViewChild('nav', {static: true}) myNav:ElementRef;

  @HostListener('window:scroll') onWindowScroll() {
    if (window.scrollY > 1.5) { 
      this.myNav.nativeElement.style.backgroundColor = '#808080';
    } else {
      this.myNav.nativeElement.style.backgroundColor = 'transparent';
      this.myNav.nativeElement.classList.remove("background-color");
    }
  }

}

HTML:

<nav #nav class="navbar navbar-expand-lg navbar-dark fixed-top">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.