Created
September 11, 2017 13:10
-
-
Save bernardo-cs/88246aeb1616e138326a5f629be3f2e3 to your computer and use it in GitHub Desktop.
Angular 2 directive scrolls into view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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