blue
blue

Reputation: 555

ngx-perfect-scrollbar: How to reference to the directive from typescript?

I'm using ngx-perfect-scrollbar with my Angular 5 project. I want to scroll the div to top when the route changes.

dashboard.html

<div class="main-panel" [perfectScrollbar] #perfectscroll>
    <router-outlet></router-outlet>
</div>

dashboard.ts

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
})
export class DashboardComponent implements OnInit {
    @ViewChild('perfectscroll') perfectscroll: PerfectScrollbarDirective;

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            this.perfectscroll.scrollToTop()
        });
    }
}

But I get this error :

TypeError: _this.perfectscroll.scrollToTop is not a function

Upvotes: 4

Views: 7206

Answers (4)

Gustavo Barros
Gustavo Barros

Reputation: 166

It worked for me

  @ViewChild(PerfectScrollbarDirective, { static: false }) perfectScrollbarDirectiveRef?: PerfectScrollbarDirective;

Upvotes: 0

Mumin Ka
Mumin Ka

Reputation: 725

All of these solutions didn't work for me. I've fixed like below

scrollUp(): void {
  const container = document.querySelector('.main-panel');
  container.scrollTop = 0;
}

Upvotes: 0

Anton Pegov
Anton Pegov

Reputation: 1474

Look at my working example.

In the trmplate:

<div class="perfectScroll" [perfectScrollbar] #psLeft="ngxPerfectScrollbar">...</div>
...
<div class="perfectScroll" [perfectScrollbar] #psRight="ngxPerfectScrollbar">...</div>

...

In the component:

@ViewChild('psLeft') psLeft: PerfectScrollbarDirective;
@ViewChild('psRight') psRight: PerfectScrollbarDirective;
...
if (this.psRight) {
    this.psRight.scrollToTop();
}

Upvotes: 6

D013
D013

Reputation: 21

just use this: @ViewChild(PerfectScrollbarDirective) perfectscroll: PerfectScrollbarDirective;

you will have instance and then you can call functions like scrollToTop()

Upvotes: 2

Related Questions