forked from ngrx/router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlink-active.ts
81 lines (72 loc) · 1.92 KB
/
link-active.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import {
AfterViewInit,
Directive,
ElementRef,
Input,
OnDestroy,
Query,
QueryList,
PLATFORM_DIRECTIVES,
provide,
Provider,
Renderer
} from 'angular2/core';
import { LinkTo } from './link-to';
import { Location } from './location';
export interface ActiveOptions {
exact: boolean;
}
/**
* The LinkActive directive toggles classes on elements that contain an active linkTo directive
*
* <a linkActive="active" linkTo="/home/page">Home Page</a>
* <ol>
* <li linkActive="active" *ngFor="var link of links">
* <a [linkTo]="'/link/' + link.id">{{ link.title }}</a>
* </li>
* </ol>
*/
@Directive({ selector: '[linkActive]' })
export class LinkActive implements AfterViewInit, OnDestroy {
@Input('linkActive') activeClass: string;
@Input() activeOptions: ActiveOptions = { exact: true };
private _sub: any;
constructor(
@Query(LinkTo) public links: QueryList<LinkTo>,
public element: ElementRef,
public location$: Location,
public renderer: Renderer
) {}
ngAfterViewInit() {
this._sub = this.location$
.map(({path}) => this.location$.prepareExternalUrl(path))
.subscribe(path => {
this.checkActive(path);
});
}
checkActive(path) {
let active = this.links.reduce((active, current) => {
let [href, query] = current.linkHref.split('?');
if (this.activeOptions.exact) {
return active ? active : href === path;
} else {
return active ? active : path.startsWith(href);
}
}, false);
let activeClasses = this.activeClass.split(' ');
activeClasses.forEach((activeClass) => {
this.renderer.setElementClass(this.element.nativeElement, activeClass, active);
});
}
ngOnDestroy() {
if (this._sub) {
this._sub.unsubscribe();
}
}
}
export const LINK_ACTIVE_PROVIDERS = [
provide(PLATFORM_DIRECTIVES, {
multi: true,
useValue: [ LinkActive ]
})
];