Search code examples
jqueryangularperfect-scrollbar

Angular2 scrollable content


I used Perfect Scrollbar and then I started using Angular 2, but I cannot find the similar addition. What would be correct way to implement perfect scrollbar in Angular 2 project?

I followed this great example but I am kind a lost how to change in ngOnInit()

jQuery(this.elementRef.nativeElement).draggable({containment:'#draggable-parent'}); 

to this=>

$(function() {
  $('#Demo').perfectScrollbar();

Solution

  • You could initialize perfect scrollbar within a custom directive with vanilla js (since it supports it ;-)) like this:

    import Ps from 'perfect-scrollable';
    
    @Directive({
      selector: '[ps]'
    })
    export class PsDirective {
      constructor(private elementRef:ElementRef) {
      }
    
      ngAfterViewInit() {
        Ps.initialize(this.elementRef.nativeElement);
      }
    }
    

    You can use / apply it like this:

    @Component({
      selector: 'app'
      template: `
        <div ps class="container">
          <div class="content"></div>
        </div>
      `,
      styles: [`
        .content {
          background-image: url('https://noraesae.github.io/perfect-scrollbar/azusa.jpg');
          width: 1280px;
          height: 720px;
        }
    
        .container {
          position: relative;
          margin: 0px auto;
          padding: 0px;
          width: 600px;
          height: 400px;
        }
      `],
      directives: [ PsDirective ]
    })
    export class App {
    }
    

    The library must have been configured before this way (css and SystemJS):

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.perfect-scrollbar/0.6.11/css/perfect-scrollbar.min.css"/>
    
    <script>
      System.config({
        transpiler: 'typescript', 
        typescriptOptions: { emitDecoratorMetadata: true }, 
        map: {
          'perfect-scrollable': 'https://cdnjs.cloudflare.com/ajax/libs/jquery.perfect-scrollbar/0.6.11/js/min/perfect-scrollbar.min.js'
        },
        packages: {
          'app': {
            defaultExtension: 'ts'
          }
        } 
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
    

    See this plunkr: https://plnkr.co/edit/S8DJpHFVNFioklTl1xg6?p=preview.