Reputation: 1051
I have a left sidebar with position fixed. what I want to achieve is that when I scroll like about 50 or 60 pixel the position of the left sidebar should be changed to fixed.
Left-sidebar.component.ts
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'left-sidebar',
templateUrl: 'left-sidebar.html',
styleUrls: ['left-sidebar.scss']
})
export class LeftSideBarComponent {
}
left-sidebar.html
<div class="col-sm-2 left-nav">
</div>
css
.left-nav {
position: absolute;
background: #424242;
height: 100%;
overflow: auto;
padding: 0;
z-index: 1;
}
How to change position of left sidebar from absolute to fixed on scroll?
Upvotes: 3
Views: 14662
Reputation: 114
I'm using Angular 4 and that solution didn't worked out for me, I tried a different aproach, because num was returning 0 on scroll. ¯_(ツ)_/¯.
I hope this will work out for you as well.
import { Inject, HostListener } from "@angular/core";
@HostListener("window:scroll", ['$event'])
onWindowScroll($event:any) {
let top = window.scrollY;
if (top > 30) {
this.fixed = true;
console.log(top);
} else if (this.fixed && top < 5) {
this.fixed = false;
console.log(top);
}
}
.fixed {
@extend .bg-white;
position: fixed;
top: 80px;
z-index: 999;
}
<div class="container" [class.fixed]="fixed">
<div class="row">
<div class="col-12">
<div ngbDropdown class="dropdown custom-dropdown">
<a class="dropdown-toggle" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown</a>
<div ngbDropdownMenu aria-labelledby="dropdownBasic1">
<a class="dropdown-item">Action - 1</a>
<a class="dropdown-item">Another Action</a>
<a class="dropdown-item">Something else is here</a>
</div>
</div>
</div>
</div>
</div>
Upvotes: 0
Reputation: 6932
I suggest you make use of the @HostListner
decorator to listen to the scroll event just like this:
import { Inject, HostListener } from "@angular/core";
import { DOCUMENT } from "@angular/platform-browser";
@Component({
moduleId: module.id,
selector: 'left-sidebar',
templateUrl: 'left-sidebar.html',
styleUrls: ['left-sidebar.scss']
})
export class LeftSideBarComponent {
public fixed: boolean = false;
constructor(@Inject(DOCUMENT) private doc: Document) {}
@HostListener("window:scroll", [])
onWindowScroll() {
let num = this.doc.body.scrollTop;
if ( num > 50 ) {
this.fixed = true;
}else if (this.fixed && num < 5) {
this.fixed = false;
}
}
add the .fixed
css to your scss file then in your template, you do the following:
<div class="col-sm-2 left-nav" [class.fixed]="fixed">
</div>
Upvotes: 8