Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 4 scrollspy not working with Angular 4

I'm trying to implement scrollspy in Angular 4. I've imported jQuery and Bootstrap.js in .angular-cli.json file. Its not giving any error in the console. However active class is not getting applied to li element as expected.

https://v4-alpha.getbootstrap.com/components/scrollspy/

header.component.ts

ngOnInit() {
    $(document).ready(() => {
        $('body').scrollspy({target: "#myNavbar", offset: 50});   
    });
}

header.component.html

<div class="navbar-collapse" id="myNavbar">
  <ul class="nav navbar-nav">
    <li><a href="#PATIENT IDENTIFICATION">Section 1</a></li>
    <li><a href="#INITIATION">Section 2</a></li>
    <li><a href="#section3">Section 3</a></li>
    <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Section 4 <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#section41">Section 4-1</a></li>
        <li><a href="#section42">Section 4-2</a></li>
      </ul>
    </li>
  </ul>
</div>
like image 253
Rahul Dagli Avatar asked Aug 02 '17 10:08

Rahul Dagli


1 Answers

It works in my case, still using ngOnInit. You can check the plukr on the below link.

http://embed.plnkr.co/JXujqbPCGXU47fccaEL6/

Please take note of.

1. Requires Bootstrap nav

Scrollspy currently requires the use of a Bootstrap nav component for proper highlighting of active links. So simply just grab a block of code from here will do.

2. Requires relative positioning

Add the position: relative; in your content where you are scrolling on. In my plunkr, I added it and the height to make the scroll basically.

.scrollspy-example {
    position: relative;
    height: 200px;
    margin-top: .5rem;
    overflow: auto;
}
like image 189
trungk18 Avatar answered Oct 14 '22 12:10

trungk18