Skip to content

Instantly share code, notes, and snippets.

@blidblid
Created September 9, 2022 08:38
Show Gist options
  • Save blidblid/b920440c7e6f68bd24a2257dca489be5 to your computer and use it in GitHub Desktop.
Save blidblid/b920440c7e6f68bd24a2257dca489be5 to your computer and use it in GitHub Desktop.
import { fromEvent, map, Observable, startWith } from 'rxjs';
export function fromQueryParams(): Observable<Record<string, string>> {
return fromEvent(window, 'popstate').pipe(
startWith(null),
map(() => {
const searchParams = new URLSearchParams(window.location.search);
const params: Record<string, string> = {};
for (const [key, value] of searchParams.entries()) {
params[key] = value;
}
return params;
})
);
}
import { Directive, Input } from '@angular/core';
@Directive({
selector: '[nativeQueryParams]',
host: {
'(click)': 'updateParams()',
'(keydown.enter)': 'updateParams()',
'(keydown.space)': 'updateParams()',
},
})
export class NativeQueryParamsDirective {
@Input('nativeQueryParams') params: Record<string, string>;
updateParams(): void {
if (!this.params) {
return;
}
const searchParams = new URLSearchParams(window.location.search);
for (const [key, value] of Object.entries(this.params)) {
searchParams.set(key, value);
}
const url = `${window.location.protocol}//${window.location.host}${
window.location.pathname
}?${searchParams.toString()}`;
window.history.pushState({ path: url }, '', url);
window.dispatchEvent(new Event('popstate'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment