Giter Club home page Giter Club logo

rx-form-mapper's Introduction

codecov npm version dependencies Status NPM License NPM bundle size semantic-release

RxFormMapper is a framework developed for angular and allows you to convert, by annotation, classes into reactive form and vice versa.

What is RxFormMapper

Reactive forms use an explicit and immutable approach to managing the state of a form at a given point in time. Each change to the form state returns a new state, which maintains the integrity of the model between changes. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously.

So... Why RxFormMapper?

Sometimes you want to transform the classes you have into reactive forms, for example you have a user model that you want to have filled out by a form:

export class User {
	name: string;
	surname: string;
	age: number;
}

So what to do? How to make a user form ? Solution is to create new instances of Reactive Form object and manually copy all properties to new object. But things may go wrong very fast once you have a more complex object hierarchy.

new FormGroup(
	name: new FormControl(user.name),
	surname: new FormControl(user.surname),
	age: new FormControl(user.age),
);

To avoid all this you can use RxFormMapper:

export class User {

	@FormControl()
	name: string;

	@FormControl()
	surname: string;

	@FormControl()
	age: number;
}
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { User } from 'src/app/models/user.model';

@Component({
	selector: 'app-user-editor',
	templateUrl: './user-editor.component.html',
	styleUrls: ['./user-editor.component.css']
})
export class UserEditorComponent {

	public form: FormGroup;
	constructor(rxFormMapper: RxFormMapper) {
		this.form = rxFormMapper.writeForm(User);
	}
}

Try it

See it in action at https://stackblitz.com/edit/rx-form-mapper-example?file=src/app/user-registration.ts

Getting started

Install npm package

npm i rx-form-mapper --save

reflect-metadata is required (with angular+ you should already have this dependency installed.)

npm i reflect-metadata --save

Import the component modules

Import the NgModule for RxFormMapper

import { RxFormMapperModule } from 'rx-form-mapper';

@NgModule({
  ...
  imports: [RxFormMapperModule.forRoot()],
  ...
})
export class MyAppModule { }

Inject RxFormMapper in your component

import { RxFormMapper } from 'rx-form-mapper';

@Component({ ... })
export class MyComponent { 
	constructor(private readonly rxFormMapper: RxFormMapper) {}
}

Build your form

import { RxFormMapper } from 'rx-form-mapper';
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { User } from 'src/app/models/user.model';

@Component({ ... })
export class MyComponent { 
	public myForm: FormGroup;
	constructor(rxFormMapper: RxFormMapper) {
		this.myForm = rxFormMapper.writeForm(new User());
	}
}

Modules

RxFormMapperModule

This module enables RxFormMapper features

Services

RxFormMapper

This service provides the methods to serialize and deserialize our objects

Methods

writeForm

This method converts our class instance into reactive form instance

this.form = formMapper.writeForm(new Post());

fromType

This method converts our class type into reactive form instance

this.form = formMapper.fromType(Post);

readForm

This method converts our form instance into specific class instance

const post: Post = formMapper.readForm(this.form, Post);

Decorators

@FormControl

If you want to expose some of properties as a FormControl, you can do it by @FormControl decorator

import { FormControl } from 'rx-form-mapper';

export class User {

	@FormControl()
	name: string;

	@FormControl()
	surname: string;

	@FormControl()
	age: number;
}

@FormGroup

If you want to expose some of properties as a FormGroup, you can do it by @FormGroup decorator

import { FormGroup } from 'rx-form-mapper';

export class Child {}

export class User {
	@FormGroup()
	child: Child;
}

@FormArray

If you want to expose some of properties as a FormArray, you can do it by @FormArray decorator

import { FormGroup } from 'rx-form-mapper';

export class Child {}

export class User {
	@FormArray(Child)
	children: Child[];
}

When you're trying to serialize a property into FormArray its required to known what type of object you are trying to convert.

@Form

If you want to add extra data to your form, you can do it by optional @Form decorator

import { Form } from 'rx-form-mapper';

@Form({
	validators: Validators.required
})
export class User {

	@FormControl()
	name: string;

	@FormControl()
	surname: string;

	@FormControl()
	age: number;
}

@CustomControl

If you want to create custom forms for specific fields, you can do it by @CustomControl decorator

Declare your custom mapper class implementing CustomControlMapper interface

import { CustomControlMapper } from 'rx-form-mapper';
import { AbstractControlOptions, FormControl } from '@angular/forms';

export class CustomAuthorControlMapper implements CustomControlMapper {

	public writeForm(value: any, abstractControlOptions: AbstractControlOptions): AbstractControl {
		return new FormControl(value, abstractControlOptions);
	}

	public readForm(control: AbstractControl): ChildTestClass {
		return control.value;
	}

}

And pass it's type as argument of CustomControl decorator

import { Form } from 'rx-form-mapper';
import { CustomAuthorControlMapper } from '.';

export class Post {

	@CustomControl(CustomAuthorControlMapper)
	author: Person;

}

Injectable CustomMapper

Sometimes you want to injects other services into your CustomMapper, RxFormMapper allows you to do it simple:

Declare your CustomControlMapper class, decorate with @Injectable and includes it in a module as a normal service.

import { CustomControlMapper } from 'rx-form-mapper';
import { AbstractControlOptions, FormControl } from '@angular/forms';

@Injectable()
export class CustomAuthorControlMapper implements CustomControlMapper {

	public writeForm(value: any, abstractControlOptions: AbstractControlOptions): AbstractControl {
		return new FormControl(value, abstractControlOptions);
	}

	public readForm(control: AbstractControl): ChildTestClass {
		return control.value;
	}

}

And pass it's type as validator or asyncValidator option

import { Form } from 'rx-form-mapper';
import { CustomAuthorControlMapper } from '.';

export class Post {

	@CustomControl(CustomAuthorControlMapper)
	author: Person;

}

Validators

If you want to set a validator on a class or a property, you can do it by specifying validators option to @Form, @FormControl,@CustomControl or @FormArray decorators

import { FormControl } from 'rx-form-mapper';

export class User {

	@FormControl({
		validators: Validators.required
	})
	completeName: string;

}

Async validators

If you want to set an AsyncValidator on a class or a property, you can do it by specifying asyncValidators option to @Form, @FormControl,@CustomControl or @FormArray decorators

import { FormControl } from 'rx-form-mapper';

const asyncValidator = (control: AbstractControl) => return of(undefined);

export class User {


	@FormControl({
		asyncValidators: asyncValidator
	})
	name: string;

}

Injectable validators

Sometimes you want to injects other services into your validator or asyncValidator, RxFormMapper allows you to do it simple with Angular Forms interfaces:

Declare your validator class implementing Validator or AsyncValidator interfaces, decorate with @Injectable and includes it in a module as a normal service.

import { AsyncValidator } from '@angular/forms';

@Injectable()
export class UniqueNameValidator implements AsyncValidator {

	constructor(private readonly http: HttpProvider) {}

	public validate(control: AbstractControl): Promise<ValidationErrors> | Observable<ValidationErrors> {
		// implementation
	}

}

And pass it's type as validator or asyncValidator option

import { FormControl } from 'rx-form-mapper';
import { UniqueNameValidator } from 'src/app/validators/unique-Name.validator';

export class User {

	@FormControl({
		asyncValidators: UniqueNameValidator
	})
	name: string;

}

Validation strategy

Sometimes you want to change the default strategy of form validation, you can do it specifying updateOn option to @Form, @FormControl,@CustomControl or @FormArray decorators

import { FormControl } from 'rx-form-mapper';

export class User {

	@FormControl({
		validators: Validators.required,
		updateOn: 'blur'
	})
	name: string;

}

rx-form-mapper's People

Contributors

kernelpanic92 avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

mdolega

rx-form-mapper's Issues

Cannot read properties of undefined (reading 'validate')

Hi, i have this part of code

@Form({
  validators: Validators.required
})
export class Login {
  @FormControl()
  email?: string;

  @FormControl()
  password?: string;
}

but, when call this.mapper.readForm(this.form, Login)i have an error, because in method
private isValidatorFn(value: any): boolean { return isFunction(value) && !value.prototype.validate; }

value.prototype is null

below part of exception:

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'validate')
TypeError: Cannot read properties of undefined (reading 'validate')
    at ValidatorResolver.isValidatorFn (rx-form-mapper.js:324)
    at ValidatorResolver.resolve (rx-form-mapper.js:310)
    at rx-form-mapper.js:295
    at Array.map (<anonymous>)
    at FormWriter.buildAbstractControlOptions (rx-form-mapper.js:295)
    at FormWriter.visitFormMetadata (rx-form-mapper.js:291)
    at FormMetadata.accept (rx-form-mapper.js:78)
    at RxFormMapper.writeForm (rx-form-mapper.js:357)

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update angular-cli monorepo (@angular-devkit/build-angular, @angular/cli)
  • chore(deps): update dependency karma-jasmine to v4.0.2
  • chore(deps): update dependency jasmine-core to v3.99.1
  • chore(deps): update dependency karma-chrome-launcher to v3.2.0
  • chore(deps): update dependency karma-coverage to v2.2.1
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update angular-cli monorepo to v17 (major) (@angular-devkit/build-angular, @angular/cli)
  • chore(deps): update codecov/codecov-action action to v4
  • chore(deps): update dependency @types/jasmine to v5
  • chore(deps): update dependency @types/node to v20
  • chore(deps): update dependency jasmine-core to v5
  • chore(deps): update dependency karma-jasmine to v5
  • chore(deps): update dependency karma-jasmine-html-reporter to v2
  • chore(deps): update dependency ng-packagr to v17
  • chore(deps): update dependency typescript to v5
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v1
  • actions/setup-node v1
  • actions/checkout v1
  • actions/setup-node v1
  • codecov/codecov-action v1
.github/workflows/release.yml
  • actions/setup-node v1
npm
package.json
  • @angular/animations 11.2.8
  • @angular/common 11.2.8
  • @angular/compiler 11.2.8
  • @angular/core 11.2.8
  • @angular/forms 11.2.8
  • @angular/platform-browser 11.2.8
  • @angular/platform-browser-dynamic 11.2.8
  • @angular/router 11.2.8
  • @types/lodash 4.14.168
  • lodash 4.17.21
  • rxjs 6.6.7
  • tslib 2.1.0
  • zone.js 0.11.4
  • @angular-devkit/build-angular 0.1102.6
  • @angular/cli 11.2.6
  • @angular/compiler-cli 11.2.8
  • @types/jasmine 3.6.9
  • @types/node 12.20.6
  • codelyzer 6.0.1
  • cz-conventional-changelog 3.3.0
  • jasmine-core 3.7.1
  • jasmine-spec-reporter 6.0.0
  • karma 6.3.1
  • karma-chrome-launcher 3.1.0
  • karma-coverage 2.0.3
  • karma-jasmine 4.0.1
  • karma-jasmine-html-reporter 1.5.4
  • ng-packagr 11.2.4
  • protractor 7.0.0
  • semantic-release 17.4.2
  • ts-node 9.1.1
  • tslint 6.1.3
  • typescript 4.1.5
projects/rx-form-mapper/package.json
  • tslib 2.1.0
  • @angular/common ^7.1.0 || ^8.0.0 || ^11.0.0
  • @angular/core ^7.1.0 || ^8.0.0 || ^11.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

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.