Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 change position to fixed on scroll

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?

like image 231
Sami Avatar asked Nov 29 '25 11:11

Sami


1 Answers

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>
like image 182
Hamed Baatour Avatar answered Dec 01 '25 00:12

Hamed Baatour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!