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

前端 未结 6 1382
广开言路
广开言路 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条回答
  •  旧时难觅i
    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

提交回复
热议问题