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

sun picture sun · Mar 21, 2019 · Viewed 104.5k times · Source

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 form).

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { QuestionService } from '../shared/question.service';

@Component({
  selector: 'app-update-que',
  templateUrl: './update-que.component.html',
  styleUrls: ['./update-que.component.scss']
})
export class UpdateQueComponent implements OnInit {

  questionsTypes = ['Text Type', 'Multiple choice', 'Single Select'];
  selectedQuestionType: string = "";
  question: any = {};

  constructor(private route: ActivatedRoute, private router: Router,
    private qService: QuestionService, private fb: FormBuilder) { 

  }

  ngOnInit() {
      this.getQuebyid();
  }

  getQuebyid(){
    this.route.params.subscribe(params => {
      this.qService.editQue([params['id']]).subscribe(res =>{
        this.question = res;
      });
    });
  }

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

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

}

if I use [(ngModule)] on my form field to set the value to my element it is working fine and showing a warning it'll be deprecated in angular 7 version.

<textarea formControlName="questioning" [(ngModule)]="question.questioning" cols="70" rows="4"></textarea>

So, I set the values to my form control by doing below but the element is not showing those values.

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

can anyone tell me how to set values to mine reactive form. Please suggest me.

Answer

wentjun picture wentjun · Mar 21, 2019

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 🙃

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!