Reactive forms in Angular

Home » Tutorials » JavaScript » Reactive forms in Angular

In the previous video we’ve discussed template driven forms in Angular. In this tutorial we will discuss reactive forms.

Reactive forms are more convenient for handling large forms and the relationships between form fields. For example, address fields can be part of a larger registration form. With reactive forms, you can react to changes in form controls and implement logic based on those changes (for example, validate the zip code based on the selected country).

The key classes of reactive forms are FormGroup (the form container), FormControl (a class for a particular control), FormBuilder (a class to quickly create controls), and FormArray (useful for dynamically adding controls).

app.ts

import {Component, OnInit} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  FormsModule,
  NonNullableFormBuilder,
  ReactiveFormsModule,
} from '@angular/forms';

interface LoginFormGroup {
  login: FormControl<string>;
  password: FormControl<string>;
  address: FormGroup<AddressFormGroup>;
}

interface AddressFormGroup {
  street: FormControl<string>;
  zipCode: FormControl<string>;
}

@Component({
  selector: 'app-root',
  imports: [
    FormsModule,
    ReactiveFormsModule

  ],
  templateUrl: './app.html',
  styleUrl: './app.scss'
})
export class App implements OnInit {

  protected form!: FormGroup<LoginFormGroup>;

  // protected form: FormGroup<LoginFormGroup> = new FormGroup<LoginFormGroup>({
  //   login: new FormControl<string>('', {
  //     nonNullable: true,
  //     validators: [Validators.required],
  //   }),
  //   password: new FormControl<string>('', {
  //     nonNullable: true,
  //     validators: [Validators.required]
  //   })
  // });

  constructor(private formBuilder: NonNullableFormBuilder) {
  }

  public ngOnInit() {
    this.form = this.formBuilder.group<LoginFormGroup>({
      login: new FormControl<string>(''),
      password: new FormControl<string>(''),
      address: new FormGroup<AddressFormGroup>({
        street: new FormControl<string>('Street'),
        zipCode: new FormControl<string>('1234')
      })
    })
  }

  protected submitForm() {
      console.log(this.form.value);
  }
}

app.html

<form [formGroup]="form" (ngSubmit)="submitForm()">
  <div>
    <label for="login">Login</label>
    <input type="text" id="login" name="login" formControlName="login">
    @if(form.controls.login.touched && form.controls.login.hasError('required')) {
      <span>Invalid control value</span>
    }
  </div>
  <div>
    <label for="password">Password</label>
    <input type="password" id="password" name="password" formControlName="password">
  </div>
  <button>Login</button>
</form>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This