[Angular] Updating and resetting FormGroups and FormControls

If you want to reset or just update field value, you can do:

reset: reset({key: value, k2:v2});

update

  1. patchValue({k: v}); update part of form fields

  2. setValue({k:v, k1: v1...}); update whole form fields.

 

reset:

  onAdd() {
    this.added.emit(this.parent.get('selector').value);
    this.parent.get('selector')
      .reset({
        quantity: 10,
        product_id: ''
      })
  }

All the 'dirty, touched, valid' props on form will also be reset.

 

Update:

  onAdd() {
    this.added.emit(this.parent.get('selector').value);
    this.parent.get('selector')
      .patchValue({
        product_id: ''
      })
  }

For 'patchValue', we only need to update part of props, not all of them. 

 

  onAdd() {
    this.added.emit(this.parent.get('selector').value);
    this.parent.get('selector')
      .setValue({
        quantity: 10,
        product_id: ''
      })
  }

For 'setValue', you have to update all the fields, otherwise it will throw error.

 

posted @ 2017-03-22 19:59  Zhentiw  阅读(241)  评论(0)    收藏  举报