Currently I have a project that uses NGRX for its store and reactive forms.
In my application, I want to map the active item in my state to the reactive forms. So in my component I have something like:
export class MyComponent {
active$: Observable<any>;
form = this.fb.group({
name: ['', [Validators.required]],
description: ['', Validators.maxLength(256)]
});
constructor(private fb: FormBuilder, private store: Store<any>) {
this.active$ = store.select(store => store.items);
}
}
In order to avoid having to subscribe to the store and select out my items, I created a directive to bind my observable to my form:
import { Directive, Input } from '@angular/core';
import { FormGroupDirective } from '@angular/forms';
@Directive({
selector: '[connectForm]'
})
export class ConnectFormDirective {
@Input('connectForm')
set data(val: any) {
if (val) {
this.formGroupDirective.form.patchValue(val);
this.formGroupDirective.form.markAsPristine();
}
}
constructor(private formGroupDirective: FormGroupDirective) { }
}
Now in my form I simply bind it like so:
<form [formGroup]="form" novalidate (ngSubmit)="onSubmit()" [connectForm]="active$ | async">
</form>
My question is:
I suppose at the end of the day for complicated scenarios you are going to have to end up subscribing to the observable in the component.
As I have already mentioned, NGXS is a state management library which is very similar to NGRX, with the difference that it has less boilerplate code and is easier to learn. There are 4 basic concepts in NGXS that you should understand before you integrate it into your project.
When should you not use NgRx? Never use NgRx if your application is a small one with just a couple of domains or if you want to deliver something quickly. It comes with a lot of boilerplate code, so in some scenarios it will make your coding more difficult.
Ngrx is the group of the Angular libraries that are used for the reactive extensions. Where Ngrx/Store usually implements patterns of Redux by using highly well-known RxJS observables about the application Angular 2.
An observable service in Angular is a singleton that can be injected into your application. It provides accessors to manipulate data (such as adding an item to an array) and storing data.
You should consider splitting your components into the "Connected" and "Presentation" components. Your connected component will be responsible for querying the store and emitting actions to the store, where your presentation component will create a form group and accept values from the store as @Input parameters. You can then listen for value changes in the form group in the presentation component and raise events with updated values to the connected component. Connected component will then handle the event from presentation component and raise a new action to update values in the store.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With