• Stars
    star
    147
  • Rank 251,347 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Sync URL Query Params with Angular Form Controls


MIT commitizen PRs styled with prettier All Contributors ngneat spectator CI

Sync URL Query Params with Angular Form Controls

The library provides a simple and reusable solution for binding URL query params to Angular Forms

Demo

Installation

npm install @ngneat/bind-query-params

Usage

Inject the BindQueryParamsFactory provider, pass an array of definitions and connect it to your form:

import { BindQueryParamsFactory } from '@ngneat/bind-query-params';

interface Filters {
  searchTerm: string;
  someBoolean: boolean;
}

@Component({
  template: `Your normal form setup`,
})
export class MyComponent {
  filters = new FormGroup({
    searchTerm: new FormControl(),
    someBoolean: new FormControl(false),
  });

  bindQueryParamsManager = this.factory
    .create<Filters>([
      { queryKey: 'searchTerm' },
      { queryKey: 'someBoolean', type: 'boolean' }
     ]).connect(this.filters);

  constructor(private factory: BindQueryParamsFactory) {}

  ngOnDestroy() {
    this.bindQueryParamsManager.destroy();
  }
}

With this setup, the manager will take care of two things:

  1. Update the control's value when the page is loaded for the first time
  2. Update the URL query parameter when the corresponding control value changes

QueryParam Definition

queryKey

The query parameter key

path

The form control path. If it is not specified, the manager assumes that the path is the queryKey. We can also pass nested keys, for example, person.name:

{ queryKey: 'name', path: 'person.name' }

type

Specify the control value type. Available options are: boolean, array, number, string and object. Before updating the control with the value, the manager will parse it based on the provided type.

parser

Provide a custom parser. For example, the default array parser converts the value to an array of strings. If we need it to be an array of numbers, we can pass the following parser:

const def = { parser: (value) => value.split(',').map((v) => +v) };

serializer

Provide a custom serializer. For example, supposing that we have a FormControl that carries a Date and we want to persist, in the query params, a custom value, such as a string Date, we can do something like the following serializer:

const def = { serializer: (value) => (value instanceof Date ? value.toISOString().slice(0, 10) : (value as string)) };

syncInitialControlValue

Set the initial control value in the URL (defaults to false)

syncInitialQueryParamValue

Sync the initial query paramater with the form group (defaults to true)

Handle Async Data

When working with async controls, such as a dropdown list whose options are coming from the server, we cannot update the control immediately. In those cases, you can set syncInitialQueryParamValue to false, which will force the control value to not be updated when the page loads.

Once the data is available, we can call the manager.syncDefs() or manager.syncAllDefs() methods to update the controls based on the current query parameters:

@Component()
export class MyComponent {
  filters = new FormGroup({
    searchTerm: new FormControl(),
    users: new FormControl([]),
    someBoolean: new FormControl(false),
  });

  bindQueryParamsManager = this.factory
    .create<Filters>([
      { queryKey: 'searchTerm' },
      { queryKey: 'someBoolean', type: 'boolean' },
      { queryKey: 'users', type: 'array', syncInitialQueryParamValue: false },
    ])
    .connect(this.filters);

  constructor(private factory: BindQueryParamsFactory) {}

  ngOnInit() {
    service.getUsers().subscribe((users) => {
      // Initalize the dropdown
      this.users = users;
      // Sync specific controls use:
      this.manager.syncDefs('users');
      // Sync all controls
      this.manager.syncAllDefs();
    });
  }

  ngOnDestroy() {
    this.bindQueryParamsManager.destroy();
  }
}

Note that syncDefs will always be called once under the hood.

Form Changes

In case the form changes after the bindQueryParamsManager's connect was called you'll need to call the reconnect method to subscribe to the new form.

@Component()
export class MyComponent {
  filters = new FormGroup({
    searchTerm: new FormControl(),
    users: new FormControl([]),
    someBoolean: new FormControl(false),
  });

  bindQueryParamsManager = this.factory
    .create<Filters>([
      { queryKey: 'searchTerm' },
    ])
    .connect(this.filters);

  constructor(private factory: BindQueryParamsFactory) {}

  ngOnInit() {
   this.filters.setControl('searchTerm', new FormControl());
   // We need to reconnect the manager due to the replacement of the control
   this.bindQueryParamsManager.reconnect(this.filters);
  }

  ngOnDestroy() {
    this.bindQueryParamsManager.destroy();
  }
}

Browser Support

The library uses the URLSearchParams API, which supported in any browser except IE.

More Repositories

1

falso

All the Fake Data for All Your Real Needs ๐Ÿ™‚
TypeScript
3,098
star
2

spectator

๐ŸฆŠ ๐Ÿš€ A Powerful Tool to Simplify Your Angular Tests
TypeScript
2,068
star
3

transloco

๐Ÿš€ ๐Ÿ˜ The internationalization (i18n) library for Angular
TypeScript
1,856
star
4

until-destroy

๐ŸฆŠ RxJS operator that unsubscribe from observables on destroy
TypeScript
1,733
star
5

elf

๐Ÿง™โ€โ™€๏ธ A Reactive Store with Magical Powers
TypeScript
1,527
star
6

content-loader

โšช๏ธ SVG component to create placeholder loading, like Facebook cards loading.
TypeScript
733
star
7

hot-toast

๐Ÿž Smoking hot Notifications for Angular. Lightweight, customizable and beautiful by default.
TypeScript
687
star
8

cashew

๐Ÿฟ A flexible and straightforward library that caches HTTP requests in Angular
TypeScript
677
star
9

reactive-forms

(Angular Reactive) Forms with Benefits ๐Ÿ˜‰
TypeScript
609
star
10

tailwind

๐Ÿ”ฅ A schematic that adds Tailwind CSS to Angular applications
TypeScript
608
star
11

query

๐Ÿš€ Powerful asynchronous state management, server-state utilities and data fetching for Angular Applications
TypeScript
555
star
12

forms-manager

๐Ÿฆ„ The Foundation for Proper Form Management in Angular
TypeScript
517
star
13

error-tailor

๐Ÿฆ„ Making sure your tailor-made error solution is seamless!
TypeScript
478
star
14

helipopper

๐Ÿš A Powerful Tooltip and Popover for Angular Applications
TypeScript
392
star
15

nx-serverless

๐Ÿš€ The Ultimate Monorepo Starter for Node.js Serverless Applications
TypeScript
388
star
16

dialog

๐Ÿ‘ป A simple to use, highly customizable, and powerful modal for Angular Applications
TypeScript
371
star
17

hotkeys

๐Ÿค– A declarative library for handling hotkeys in Angular applications
TypeScript
325
star
18

edit-in-place

A flexible and unopinionated edit in place library for Angular applications
TypeScript
252
star
19

svg-icon

๐Ÿ‘ป A lightweight library that makes it easier to use SVG icons in your Angular Application
TypeScript
251
star
20

inspector

๐Ÿ•ต๏ธ An angular library that lets you inspect and change Angular component properties
TypeScript
218
star
21

dirty-check-forms

๐ŸฌDetect Unsaved Changes in Angular Forms
TypeScript
199
star
22

input-mask

๐ŸŽญ @ngneat/input-mask is an angular library that creates an input mask
TypeScript
199
star
23

lib

๐Ÿค– Lets you focus on the stuff that matters
TypeScript
180
star
24

transloco-keys-manager

๐Ÿฆ„ The Key to a Better Translation Experience
TypeScript
174
star
25

dag

๐Ÿ  An Angular service for managing directed acyclic graphs
TypeScript
153
star
26

from-event

๐ŸฆŠ ViewChild and FromEvent โ€” a Match Made in Angular Heaven
TypeScript
137
star
27

overview

๐Ÿค– A collection of tools to make your Angular views more modular, scalable, and maintainable
TypeScript
118
star
28

aim

Angular Inline Module Schematics
TypeScript
97
star
29

cmdk

Fast, composable, unstyled command menu for Angular. Directly inspired from pacocoursey/cmdk
TypeScript
91
star
30

copy-to-clipboard

โœ‚๏ธ Modern copy to clipboard. No Flash.
TypeScript
78
star
31

variabless

JS & CSS - A Match Made in Heaven ๐Ÿ’Ž
HTML
78
star
32

loadoff

๐Ÿคฏ When it comes to loaders, take a load off your mind...
TypeScript
78
star
33

effects

๐Ÿช„ A framework-agnostic RxJS effects implementation
TypeScript
63
star
34

avvvatars

Beautifully crafted unique avatar placeholder for your next angular project.
TypeScript
46
star
35

react-rxjs

๐Ÿ”Œ "Plug and play" for Observables in React Apps!
TypeScript
37
star
36

subscribe

Subscription Handling Directive
TypeScript
34
star
37

elf-ng-router-store

Bindings to connect Angular router to Elf
TypeScript
24
star
38

ng-standalone-nx

TypeScript
24
star
39

lit-file-generator

๐ŸŽ A lit generator for a component, directive, and controller.
JavaScript
19
star
40

storage

TypeScript
18
star
41

material-schematics

TypeScript
3
star
42

svg-icon-demo

TypeScript
1
star