angularangular2-observablesangular-reactive-forms

How to populate a form from a list to update in Angular2?


I am new to angular. I have created reactive forms. I need to populate the form with values from a GET REST call so that I can update.

The list and form are different components. Clicking on edit on list should take me to a new url with populated values. Should I implement it with @Input or observables? Kindly point to some examples.


Solution

  • To change the value of a control built via reactive forms paradigm, use the AbstractControl#setValue or AbstractControl#patchValue methods. The first argument is the new value you want to set.

    Here's an example of usage.

    form = this.fb.group({
      username: ''
    })
    
    ngOnInit() {
      this.form.setValue({username: 'Name'})
    }
    

    The difference between setValue and patchValue is that setValue is stricter: it won't allow any missing or extra fields on case of updating FormGroup's value. For example, say we're given the form built like this.

    form = this.fb.group({
      username: '',
      password: '',
    })
    

    And we want to update only the password. The following will work.

    this.form.patchValue({password: '123456'})
    

    But the following will fail because we didn't provide a value for the username control.

    this.form.setValue({password: '123456'}) // runtime Angular error