From 7c921a9ccec7fd30d1ae0c3e3f5dd0a1e7d25cc3 Mon Sep 17 00:00:00 2001 From: Timothy Alcaide Date: Sun, 21 Jul 2024 18:50:08 +0200 Subject: [PATCH] feat: with router and filter sync, to bind route with filter in queryparams --- .../src/lib/with-router-filter-sync.ts | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 libs/ngrx-toolkit/src/lib/with-router-filter-sync.ts diff --git a/libs/ngrx-toolkit/src/lib/with-router-filter-sync.ts b/libs/ngrx-toolkit/src/lib/with-router-filter-sync.ts new file mode 100644 index 0000000..f29068f --- /dev/null +++ b/libs/ngrx-toolkit/src/lib/with-router-filter-sync.ts @@ -0,0 +1,38 @@ +import { effect, inject } from '@angular/core'; +import { Router, ActivatedRoute } from '@angular/router'; +import { patchState, signalStoreFeature, type, withHooks } from '@ngrx/signals'; +import { Filter } from './with-data-service'; + +export function withRouterFilterSync() { + return signalStoreFeature( + { + state: type<{ filter: F }>(), + }, + withHooks({ + onInit(store) { + const router = inject(Router) + const route = inject(ActivatedRoute) + const filterKeys = Object.keys(store.filter()); + const queryParams = route.snapshot.queryParams; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const filter = filterKeys.reduce((acc: any, key: string) => { + if (queryParams['hasOwn'](key)) { + acc[key] = queryParams[key]; + } + return acc; + }, {} as F); + + patchState(store, { filter }); + + effect(() => { + router.navigate([], { + relativeTo: route, + queryParams: store.filter(), + queryParamsHandling: 'merge', + }); + }); + }, + }) + ); +}