Angular5 自定義scrollbar樣式之 ngx-perfect-scollbar

版本

  • angular 5.0
  • ngx-perfect-scrollbar ^5.3.5

爲何不用 ngx-perfect-scrollbar 最新的版本 v7 呢?css

由於它報錯啊!!! 每次init的時候,就報一個Object() is not a function。 根據GitHub上熱心網友的建議,就downgrade了。html

詳見:https://github.com/zefoy/ngx-perfect-scrollbar/issues/189node

安裝

npm 安裝沒啥好說的
npm install --save ngx-perfect-scrollbar@^5.0.0git

使用

1. 導入module

// app.module.ts
import { PerfectScrollbarModule, PerfectScrollbarConfigInterface, PERFECT_SCROLLBAR_CONFIG } from 'ngx-perfect-scrollbar';

const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = {
  wheelPropagation: true
};

@NgModule({
  bootstrap: [
    AppComponent
  ],
  declarations: [
    ... 
  ],
  imports: [
    ..., 
    PerfectScrollbarModule
  ],
  exports: [
  ],
  providers: [
    {
      provide: PERFECT_SCROLLBAR_CONFIG,
      useValue: DEFAULT_PERFECT_SCROLLBAR_CONFIG
    }
  ]
})
export class AppModule {}

Providing the global configuration is optional and when used you should only provide the configuration in your root module.
提供全局配置是可選的,可是若是你須要使用,那麼只須要在應用的root module中配置。github

2. 在模板中使用

API 提供了兩種使用方式,一種是 Component 使用方式,一種是 Derective使用方式。我在項目中用的後者。npm

<ul *ngIf="nodeList.length" class="indented mTop scroll"  [style.max-height.px]="treeContentHeight" [perfectScrollbar]="config">
        <li class="no_line" *ngFor="let node of nodeList"></li>
</ul>
import { PerfectScrollbarConfigInterface, PerfectScrollbarDirective } from 'ngx-perfect-scrollbar';

public config: PerfectScrollbarConfigInterface = {};
@ViewChild(PerfectScrollbarDirective) directiveRef?: PerfectScrollbarDirective;

3. 導入CSS

// styles.scss
@import '~perfect-scrollbar/css/perfect-scrollbar.css';

效果:
bootstrap

遇到的問題

上中下結構中,只讓 content部分有滾動條,可是路由跳轉後,滾動條的高度沒有從新計算。

解決方案:app

// home.component.html
<div class="container">
    <div class="header">
        <app-header></app-header>
    </div>
    <div class="content" [perfectScrollbar]="config">
        <router-outlet></router-outlet>
    </div>
    <div class="footer">
        <app-footer></app-footer>
    </div>
</div>

在路由跳轉後,須要調用update()更新scrollbar的size 和 positionide

import { Component, OnInit, ViewChild } from '@angular/core';
import { Router} from '@angular/router';
import { PerfectScrollbarConfigInterface, PerfectScrollbarDirective } from 'ngx-perfect-scrollbar';


@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
    public config: PerfectScrollbarConfigInterface = {};
    @ViewChild(PerfectScrollbarDirective) directiveRef?: PerfectScrollbarDirective;
    constructor(public _router: Router) { }

    ngOnInit() {
        this._router.events.subscribe((event) => {
            // update the scrollbar
            this.directiveRef.update();
          });
    }

}
相關文章
相關標籤/搜索