I want to auto save content in reactive form when form is valid without clicking save button.
How to implement auto save a reactive form in angular 4?
7k views Asked by Saroz Maharjan At
3
There are 3 answers
0
On
Don't forget to unsubscribe at the end. You should capture your subscriptions and unsubscribe them at the end. to avoid any memory leaks.
import { Subscription } from 'rxjs/subscription';
@Component({...})
export class MyComponent {
...
subscription = new Subscription;
...
ngOnInit() {
this.subscription.add(this.form.statusChanges()
.takeWhile(this.alive)
.subscribe(status => {
//do whatever
});
ngOnDestroy() {
this.subscription.unsubscribe();
}
0
On
If you have asynchronous validators the option below will only save the form after the validators have been executed and no errors have been reported
formControl.statusChanges
.pipe(
filter((status) => status === 'VALID'),
withLatestFrom(formControl.valueChanges),
map(([_status, value]) => value),
switchMap(value=>this.service.save(value)) // if you are using a service
takeUntil(this.destroy$)
)
.subscribe((value) => {
//if you've been using NGRX for example
this.store.dispatch(action)
});
You will want to subscribe to the
statusChanges()
method of your FormGroup, and in that Observable you can determine whether the FormGroup is valid and then trigger a save event.