How to Get the Form Control Value in Angular?

A FormControl in Angular is an object that encapsulates the information related to a form element such as an input, dropdown, textarea, etc. It always keeps track of the value and the validation that the related form element has.

It means you can any time get the value of the FormControl from the template file to the .ts file.

Let’s say we have the following FormGroup which has three FormControls named userName, email, and phone:

this.userForm = this.formBuilder.group({
      userName: new FormControl('', [Validators.required]),
      email: new FormControl('', [Validators.required]),
      phone: new FormControl('')
});

So now, if we want to get the value of the userName FormControl, we can use the following code:

this.userForm.get('userName').value

OR, we can also use the following code as well. This will also return the same value as above:

this.userForm.controls['userName'].value

Setting the Form Control Value

To set the value of a FormControl dynamically, we can use the setValue() method.

The code written below will set the value of the userName to ‘John Doe’:

this.userForm.get('userName').setValue('John Doe');

OR you can also use the following approach. This will also set the userName to ‘John Doe’:

this.userForm.controls['userName'].setValue('John Doe');

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts