Skip to content

Instantly share code, notes, and snippets.

@bernardo-cs
Created September 11, 2017 13:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bernardo-cs/88246aeb1616e138326a5f629be3f2e3 to your computer and use it in GitHub Desktop.
Save bernardo-cs/88246aeb1616e138326a5f629be3f2e3 to your computer and use it in GitHub Desktop.
Angular 2 directive scrolls into view
import { AfterViewInit, Directive, ElementRef, Input, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
@Directive({
selector: '[flScrollBulletinIntoView]'
})
export class ScrollBulletinIntoViewDirective implements AfterViewInit, OnDestroy {
@Input() bulletinId: number;
private scrollIntoView$: Subscription;
constructor(private el: ElementRef,
private route: ActivatedRoute,
private router: Router) { }
ngAfterViewInit() {
this.scrollIntoView$ = this.route.params.map(params => params.bulletin)
.distinctUntilChanged()
.map(bulId => +bulId)
.filter(bulId => this.bulletinId === bulId)
.do(() => {
this.router.navigate([{}], {relativeTo: this.route});
this.el.nativeElement.scrollIntoView();
})
.subscribe()
}
ngOnDestroy(): void {
this.scrollIntoView$.unsubscribe();
}
}
Usage Example:
<div flScrollBulletinIntoView
[bulletinId]="bulletinsChapter?.bulletin?.id"
[ngSwitch]="bulletinsChapter?.bulletin?.kind" class="print-break">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment