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)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With