Created
April 30, 2025 04:06
-
-
Save nathonius/134fedc85256b0b40bccb799b292473b to your computer and use it in GitHub Desktop.
Angular routerLinkStatus 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 { | |
booleanAttribute, | |
Directive, | |
effect, | |
ElementRef, | |
inject, | |
input, | |
Renderer2, | |
} from '@angular/core'; | |
import { RouterLinkActive } from '@angular/router'; | |
import type { Subscription } from 'rxjs'; | |
/** | |
* Link routerLinkActive, but with a class applied when active | |
* AND a class applied when inactive | |
*/ | |
@Directive({ | |
selector: '[routerLinkStatus]', | |
standalone: true, | |
hostDirectives: [RouterLinkActive], | |
}) | |
export class RouterLinkStatusDirective { | |
public readonly routerLinkStatus = input.required<{ | |
active: string; | |
inactive: string; | |
}>(); | |
public readonly statusExact = input(false, { transform: booleanAttribute }); | |
public readonly routerLinkActive = inject(RouterLinkActive, { self: true }); | |
public readonly elementRef = inject(ElementRef); | |
public readonly renderer = inject(Renderer2); | |
private subscription: Subscription | undefined; | |
constructor() { | |
effect(() => { | |
this.subscription?.unsubscribe(); | |
const { active, inactive } = this.routerLinkStatus(); | |
this.routerLinkActive.routerLinkActive = active; | |
this.routerLinkActive.routerLinkActiveOptions = { | |
exact: this.statusExact(), | |
}; | |
this.subscription = this.routerLinkActive.isActiveChange.subscribe( | |
(isActive) => { | |
if (isActive) { | |
this.renderer.removeClass(this.elementRef.nativeElement, inactive); | |
} else { | |
this.renderer.addClass(this.elementRef.nativeElement, inactive); | |
} | |
} | |
); | |
if (!this.routerLinkActive.isActive) { | |
this.renderer.addClass(this.elementRef.nativeElement, inactive); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment