Reactive Forms - FormControl Basics, Set & Get Values

Reactive forms are used when the form is complex, has many input fields, and needs better control like validation on focus, blur, or click.

If there is only one input field, reactive forms are not required.

Reactive forms are recommended over template-driven forms for large and enterprise applications.


When NOT to Use Reactive Forms

If you have:

  1. Only one input field
  2. Very simple form
  3. No complex validation

Then you can use template-driven forms or directly read input values.


Using Reactive Forms with Input Fields (Basic)

Here we are not using <form> tag.

We are directly using input fields with FormControl.


App Component (app.ts)

import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';

@Component({
selector: 'app-root',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './app.html'
})
export class App {

email = new FormControl('');
password = new FormControl('');

login() {
console.log(this.email.value);
console.log(this.password.value);
}

reset() {
this.email.setValue('');
this.password.setValue('');
}
}


App HTML (app.html)

<input
type="text"
placeholder="Enter Email"
[formControl]="email"
/>

<br><br>

<input
type="password"
placeholder="Enter Password"
[formControl]="password"
/>

<br><br>

<button (click)="login()">Login</button>
<button (click)="reset()">Reset</button>

<br><br>

<ul>
<li>Email: {{ email.value }}</li>
<li>Password: {{ password.value }}</li>
</ul>


Important Points

  1. FormControl is used to bind input fields
  2. [formControl] connects input with FormControl
  3. ReactiveFormsModule must be imported
  4. .value is used to get input value
  5. setValue() is used to update or reset value
  6. Reactive forms work with inputs even without <form> tag