Created
May 8, 2020 12:29
-
-
Save jrybinski/19595459f77f495ef5b54379dade41e9 to your computer and use it in GitHub Desktop.
Angular router link custom directive
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 { Directive, HostListener, Input } from '@angular/core'; | |
| import { ActivatedRoute, QueryParamsHandling, Router } from '@angular/router'; | |
| @Directive({ | |
| selector: '[link]' | |
| }) | |
| export class LinkDirective { | |
| @Input() link: string | string[]; | |
| @Input() linkQueryParams: object; | |
| @Input() linkQueryParamsHandling: QueryParamsHandling = ''; | |
| @Input() linkIsActive = true; | |
| @HostListener('click', ['$event']) | |
| onClick($event) { | |
| if (!this.linkIsActive) { | |
| return; | |
| } | |
| // ctrl+click, cmd+click | |
| if ($event.ctrlKey || $event.metaKey) { | |
| $event.preventDefault(); | |
| $event.stopPropagation(); | |
| window.open(this.getUrl(), '_blank'); | |
| } else { | |
| this.router.navigate(this.getLink(), {queryParams: this.linkQueryParams, queryParamsHandling: this.linkQueryParamsHandling}); | |
| } | |
| } | |
| @HostListener('mouseup', ['$event']) | |
| onMouseUp($event) { | |
| if (!this.linkIsActive) { | |
| return; | |
| } | |
| // middleclick | |
| if ($event.which === 2) { | |
| $event.preventDefault(); | |
| $event.stopPropagation(); | |
| window.open(this.getUrl(), '_blank'); | |
| } | |
| } | |
| constructor(private router: Router, private activatedRoute: ActivatedRoute) { | |
| } | |
| private getLink(): string[] { | |
| const { link } = this; | |
| if (!Array.isArray(link)) { | |
| return [link]; | |
| } | |
| return link; | |
| } | |
| private getUrl(): string { | |
| const oldQueryParams = this.activatedRoute.snapshot.queryParams; | |
| const { link, linkQueryParams } = this; | |
| const mergedQueryParams = { | |
| ...oldQueryParams, | |
| ...linkQueryParams | |
| }; | |
| let url = ''; | |
| if (Array.isArray(link)) { | |
| url = link[0]; | |
| if (link[1]) { | |
| url += '/' + link[1]; | |
| } | |
| } else { | |
| url = link; | |
| } | |
| if (mergedQueryParams) { | |
| url += '?'; | |
| for ( const param of Object.keys(mergedQueryParams)) { | |
| url += `${param}=${mergedQueryParams[param]}&`; | |
| } | |
| } | |
| return url; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment