Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Scrollspy & Affix in Angular 2

I noticed that you cannot use in angular 2 components bootstrap feature like data-spy="affix"

Does anyone know how to use affix and scrollspy in angular 2? (Example)

like image 545
Gerald Hughes Avatar asked Sep 12 '16 13:09

Gerald Hughes


People also ask

How does Bootstrap Scrollspy work?

Scrollspy works according to the scroll position or the position at which the user is currently is seeing. Bootstrap scrollspy targets the navigation bar contents automatically on scrolling the area.

How do you use scroll spy?

Add data-spy="scroll" to the element that should be used as the scrollable area (often this is the <body> element). Then add the data-target attribute with a value of the id or the class name of the navigation bar ( . navbar ). This is to make sure that the navbar is connected with the scrollable area.

How do you make a Scrollspy in HTML?

To create a scrollspy, use the data-bs-spy=” scroll” attribute to make the required area scrollable. For example, we choose html body as the scrollable area. Give ID or class name of the navigation bar to data-bs-target attribute to connect navbar or list-group with scrollable area.


1 Answers

You could write your small directive which would do the same thing. I'm sharing my code:

Directive:

@Directive({
 selector: '[scrollPoint]'
})
export class ScrollPointDirective {
   @Input() scrollPoint: number;
   constructor(
    @Inject(DOCUMENT) private document: Document,
    private renderer: Renderer,
    private el: ElementRef
 ) { }

   @HostListener('window:scroll', [])
   onWindowScroll() {
      const windowScroll = this.document.body.scrollTop;
      if (windowScroll > this.scrollPoint) {
        //add class to the native element
        this.renderer.setElementClass(this.el.nativeElement, 'sticky-nav', true);
      } else {
        //remove class from native element
        this.renderer.setElementClass(this.el.nativeElement, 'sticky-nav', false);
      }

   }

 }

The @Input scrollPoint parameter can be passed from your HTML

HTML:

 <div [scrollPoint]="235">
    <ul class="nav-stacked">
       //your code
    </ul>
 </div>

Add CSS to the class added in the directive:

CSS

.sticky-nav {
  position: sticky;
  top: 90px;
  bottom: 0;
 }

I haven't been able to integrate affix to angular2 as well, but this did it for me. Hope it helps.

like image 184
Antara Datta Avatar answered Oct 21 '22 11:10

Antara Datta