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:
- Is this a good idea / is there a better way to handle this?
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.