Giter VIP home page Giter VIP logo

bind-query-params's Introduction


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.

bind-query-params's People

Contributors

cbejensen avatar gili-lumigo avatar netanelbasal avatar rafaelss95 avatar shaharkazaz avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.