How to set value to form control in Reactive Forms in Angular

前端 未结 6 1375
广开言路
广开言路 2020-11-28 08:15

Hi Everyone I\'m new to angular. Actually, I\'m trying to subscribe data from a service and that data, I\'m passing to form control of mine from (example, it\'s like an edit

相关标签:
6条回答
  • 2020-11-28 08:36

    Use patchValue() method which helps to update even subset of controls.

    setValue(){
      this.editqueForm.patchValue({user: this.question.user, questioning: this.question.questioning})
    }
    


    From Angular docs setValue() method:

    Error When strict checks fail, such as setting the value of a control that doesn't exist or if you excluding the value of a control.

    In your case, object missing options and questionType control value so setValue() will fail to update.

    0 讨论(0)
  • 2020-11-28 08:37

    To assign value to a single Form control/individually, I propose to use setValue in the following way:

    this.editqueForm.get('user').setValue(this.question.user);
    
    this.editqueForm.get('questioning').setValue(this.question.questioning);
    
    0 讨论(0)
  • 2020-11-28 08:39

    Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

    patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

    In this scenario, we will want to use patchValue, since we are only updating user and questioning:

    this.qService.editQue([params["id"]]).subscribe(res => {
      this.question = res;
      this.editqueForm.patchValue({
        user: this.question.user,
        questioning: this.question.questioning
      });
    });
    

    EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead

    0 讨论(0)
  • 2020-11-28 08:47

    In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).

    setValue:

    • Initialize Model Structure in Constructor:

      this.newForm = this.formBuilder.group({  
         firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
         lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
      });
      
    • If you want to update all fields of form:

      this.newForm.setValue({
         firstName: 'abc',
         lastName: 'def'
      });
      
    • If you want to update specific field of form:

      this.newForm.controls.firstName.setValue('abc');
      

    Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.

    patchValue:

    • If you want to update some/ specific fields of form:

      this.newForm.patchValue({
         firstName: 'abc'
      });
      

    Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.

    0 讨论(0)
  • 2020-11-28 08:47

    Try this.

    editqueForm =  this.fb.group({
       user: [this.question.user],
       questioning: [this.question.questioning, Validators.required],
       questionType: [this.question.questionType, Validators.required],
       options: new FormArray([])
    })
    

    setValue and patchValue

    if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

    formgroup.setValue({name: ‘abc’, age: ‘25’}); It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

    On the other hand patchvalue is a lot easier on that part, let’s say you only want to assign the name as a new value:

    formgroup.patchValue({name:’abc’});

    0 讨论(0)
  • 2020-11-28 08:50

    The "usual" solution is make a function that return an empty formGroup or a fullfilled formGroup

    createFormGroup(data:any)
    {
     return this.fb.group({
       user: [data?data.user:null],
       questioning: [data?data.questioning:null, Validators.required],
       questionType: [data?data.questionType, Validators.required],
       options: new FormArray([this.createArray(data?data.options:null])
    })
    }
    
    //return an array of formGroup
    createArray(data:any[]|null):FormGroup[]
    {
       return data.map(x=>this.fb.group({
            ....
       })
    }
    

    then, in SUBSCRIBE, you call the function

    this.qService.editQue([params["id"]]).subscribe(res => {
      this.editqueForm = this.createFormGroup(res);
    });
    

    be carefull!, your form must include an *ngIf to avoid initial error

    <form *ngIf="editqueForm" [formGroup]="editqueForm">
       ....
    </form>
    
    0 讨论(0)
提交回复
热议问题