2017-05-23 7 views
2

私は位置が固定された左側のサイドバーを持っています。私が達成したいことは、約50または60ピクセルのようにスクロールすると、左側のサイドバーの位置を固定に変更する必要があるということです。角度2スクロールで固定位置に変更

左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 { 
} 

左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; 
} 

ホー左のサイドバーの位置をスクロールの絶対値から固定値に変更するには?

答えて

5

私はちょうどこのように、スクロールイベントに耳を傾ける@HostListnerデコレータを利用することをお勧め:

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; 
      } 
     } 

があなたのテンプレートで、あなたのSCSSファイルに.fixed CSSを追加 、あなたは、次の操作を行います

<div class="col-sm-2 left-nav" [class.fixed]="fixed"> 

</div> 
+0

ありがとう私はこれを見つけました:http://brianflove.com/2016/10/10/angular-2-window-scroll-event-using-hostlistener/ – Sami

関連する問題