-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(navigation-class-handler): new utility to add/remove a css class…
… on the body while navigating
- Loading branch information
1 parent
40cd715
commit 6dd1466
Showing
3 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
43 changes: 43 additions & 0 deletions
43
libs/components/src/lib/navigation-class-handler/navigation-class-handler.ts
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { DOCUMENT } from '@angular/common' | ||
import { APP_INITIALIZER, EnvironmentProviders, makeEnvironmentProviders } from '@angular/core' | ||
import { NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Router } from '@angular/router' | ||
import { delay, filter, switchMap, take, tap } from 'rxjs' | ||
|
||
function provideNavigationClassHandlerFactory( | ||
this: undefined, | ||
className: string, | ||
doc: Document, | ||
router: Router, | ||
): () => Promise<void> { | ||
return () => { | ||
const navigationEnd$ = router.events.pipe( | ||
filter((ev) => ev instanceof NavigationEnd || ev instanceof NavigationCancel || ev instanceof NavigationError), | ||
) | ||
|
||
router.events | ||
.pipe( | ||
filter((e) => e instanceof NavigationStart), | ||
tap(() => doc.body.classList.add(className)), | ||
switchMap(() => navigationEnd$.pipe(take(1), delay(0))), | ||
tap(() => doc.body.classList.remove(className)), | ||
) | ||
.subscribe() | ||
|
||
// since we provide the factory as `APP_INITIALIZER` to get called, we need to return a promise | ||
return Promise.resolve() | ||
} | ||
} | ||
|
||
/** | ||
* sets up a handler which adds the provided css class to the document#body while angular router is navigating | ||
*/ | ||
export function provideNavigationClassHandler(className: string): EnvironmentProviders { | ||
return makeEnvironmentProviders([ | ||
{ | ||
provide: APP_INITIALIZER, | ||
multi: true, | ||
useFactory: provideNavigationClassHandlerFactory.bind(void 0, className), | ||
deps: [DOCUMENT, Router], | ||
}, | ||
]) | ||
} |
This file contains 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