How to implement auto save a reactive form in angular 4?

有些话、适合烂在心里 提交于 2019-12-10 09:46:54

问题


I want to auto save content in reactive form when form is valid without clicking save button.


回答1:


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.

import 'rxjs/add/operator/takeWhile';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({...})
export class MyComponent {

  private form: FormGroup;
  private alive: boolean;

  constructor(private formBuilder: FormBuilder) {}

  public ngOnInit(): void {
    this.alive = true;
    this.form = this.formBuilder.group({
      // your form configuration
    });

    this.form.statusChanges()
      .takeWhile(this.alive) // only subscribe while this component is alive
      .subscribe((status) => {
        // if status is valid, auto-save
      });
  }

  public void ngOnDestroy() {
    this.alive = false;
  }
}



回答2:


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();
 }


来源:https://stackoverflow.com/questions/46094431/how-to-implement-auto-save-a-reactive-form-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!