Manually Set Value for FormBuilder Control

前端 未结 11 1065
执笔经年
执笔经年 2020-11-27 11:25

This is driving me nuts, I\'m under the gun and can\'t afford to spend another whole day on this.

I am trying to manually set a control value (\'dept\') within the c

相关标签:
11条回答
  • 2020-11-27 11:43
      let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
      this.form.complexForm.patchValue(cloneObj);
    

    If you don't want manually set each field.

    0 讨论(0)
  • 2020-11-27 11:48

    I know the answer is already given but I want give a bit brief answer how to update value of a form so that other new comers can get a clear idea.

    your form structure is so perfect to use it as an example. so, throughout my answer I will denote it as the form.

    this.form = this.fb.group({
        'name': ['', Validators.required],
        'dept': ['', Validators.required],
        'description': ['', Validators.required]
      });
    

    so our form is a FormGroup type of object that has three FormControl.

    There are two ways to update the model value:

    • Use the setValue() method to set a new value for an individual control. The setValue() method strictly adheres to the structure of the form group and replaces the entire value for the control.

    • Use the patchValue() method to replace any properties defined in the object that have changed in the form model.

    The strict checks of the setValue() method help catch nesting errors in complex forms, while patchValue() fails silently on those errors.

    From Angular official documentation here

    so, When updating the value for a form group instance that contains multiple controls, but you may only want to update parts of the model. patchValue() is the one you are looking for.

    lets see example. When you use patchValue()

    this.form.patchValue({
        dept: 1 
    });
    //here we are just updating only dept field and it will work.
    

    but when you use setValue() you need to update the full model as it strictly adheres the structure of the form group. so, if we write

    this.form.setValue({
        dept: 1 
    });
    // it will throw error.
    

    We must pass all the properties of the form group model. like this

    this.form.setValue({
          name: 'Mr. Bean'
          dept: 1,
          description: 'spome description'
      });
    

    but I don't use this style frequently. I prefer using the following approach that helps to keep my code cleaner and more understandable.

    What I do is, I declare all the controls as a seperate variable and use setValue() to update that specific control.

    for the above form, I will do something like this.

    get companyIdentifier(): FormControl {
        return this.form.get('name') as FormControl;
    }
    
    get dept(): FormControl {
        return this.form.get('dept') as FormControl;
    }
    
    get description(): FormControl {
        return this.form.get('description') as FormControl;
    }
    

    when you need to update the form control just use that property to update it. In the example the questioner tried to update the dept form control when user select an item from the drop down list.

    deptSelected(selected: { id: string; text: string }) {
      console.log(selected) // Shows proper selection!
    
      // instead of using this.form.controls['dept'].setValue(selected.id), I prefer the following.
    
      this.dept.setValue(selected.id); // this.dept is the property that returns the 'dept' FormControl of the form.
    }
    

    I suggest to have a look FormGroup API to get know how of all the properties and methods of FormGroup.

    Additional: to know about getter see here

    0 讨论(0)
  • 2020-11-27 11:51

    Updated: 19/03/2017

    this.form.controls['dept'].setValue(selected.id);
    

    OLD:

    For now we are forced to do a type cast:

    (<Control>this.form.controls['dept']).updateValue(selected.id)
    

    Not very elegant I agree. Hope this gets improved in future versions.

    0 讨论(0)
  • 2020-11-27 11:51

    You could try this:

    deptSelected(selected: { id: string; text: string }) {
      console.log(selected) // Shows proper selection!
    
      // This is how I am trying to set the value
      this.form.controls['dept'].updateValue(selected.id);
    }
    

    For more details, you could have a look at the corresponding JS Doc regarding the second parameter of the updateValue method: https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L269.

    0 讨论(0)
  • 2020-11-27 11:52

    If you are using form control then the simplest way to do this:

    this.FormName.get('ControlName').setValue(value);
    
    0 讨论(0)
提交回复
热议问题