Reactive Forms in Angular

angular

Reactive Forms in Angular form one of the two types of Forms in Angular, namely:
– Template Driven Forms
– Reactive Forms

Reactive forms uses a model driven approach to handling inputs and it’s changes over time. It enable the developers to get more granular control of the forms.

Features of Reactive Forms

  • Dynamically add/remove form controls
  • Use custom Validators
  • Change validators dynamically

To get started with Reactive Forms Module, make sure to import it in AppModule.

// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  ...
  imports: [
    ...
    ReactiveFormsModule
  ]
})
export class AppModule { ... }

Build a Reactive Form

Let’s create a UserDetailsEditor component, which will hold a form to modify the UserDetails.
We will start with some basic information like Name and Age.

// user-details-editor.component.ts
@Component({
})
export class UserDetailsEditorComponent {
  userDetailsForm = new FormGroup({
    name: new FormControl('Sam'),
    age: new FormControl(10)
  });

  onSubmitClick() {
    console.log('name', this.userDetailsForm.value.name)
    console.log('age', this.userDetailsForm.value.age)
  }
}

Now we need to represent this form model to a Form instance in the HTML

// user-details-editor.component.html
<form class="example-form" [formGroup]="userDetailsForm">
  <mat-form-field class="example-full-width" appearance="fill">
    <mat-label>Name</mat-label>
    <input matInput placeholder="Prometheus" formControlName="name">
  </mat-form-field>
  <mat-form-field class="example-full-width" appearance="fill">
    <mat-label>Age</mat-label>
    <input matInput placeholder="10" formControlName="age">
  </mat-form-field>
</form>
<button mat-raised-button color="primary" (click)="onSubmitClick()">Submit</button>

Now that the template is tightly bound to the userDetailsForm instance, any changes to the form will be accessible via the value property.

If you run the above example, it should display the instantiated values in the UI:

reactive form init

Now, if you update the values of Name to Samuel and Age to 15, and hit Submit, then the new values should be logged to the console via the onSubmitClick() function

after form changed

In the above example, we used the Submit button click to get the values.
But we can also track the live changes of the form, and perform actions based on it. For this ReactiveForms expose the valueChanges subscription.
To do that we can attach a callback when the form initialization is complete. In this case, we will use the ngOnInit() hook

ngOnInit(): void {
  this.userDetailsForm.valueChanges.subscribe(changedValues => {
    console.log('changed values', changedValues);
  });
}

The result log during changing the values would be

listening to valueChanges on the form

We can also attach this subscription to any individual control. For example, we can attach to ‘name‘ using below code:

(this.userDetailsForm.get('name') as FormControl).valueChanges.subscribe(changedValues => {
  console.log('changing name', changedValues);
});

This is the basics of creating Reactive Forms in Angular. For more details on Angular, please click here.

Leave a Reply