Solution: Implement Reactive Form

Execute a possible solution for the exercise presented in the previous lesson.

Let’s break the solution down and describe its most essential parts.

Component class

We define the RegistrationForm interface with two string form controls to leverage the full potential of typed forms.

interface RegistrationForm {
    username: FormControl<string>;
    email: FormControl<string>;
}

Remember: Usually, it’s good practice to have model objects in a standalone file, but for the sake of the conciseness of the demo, we placed it inside the component class.

We use the interface as the type for our form, which provides all the benefits of typed forms, and we set an empty string as the initial value for both properties. Since we want the user to enter at least five characters for the username field, we also add two built-in validators:

readonly usernameMinLength = 5;

registrationForm: FormGroup<RegistrationForm>;

ngOnInit(): void {
  this.registrationForm = this.fb.group({
     username: ['', [Validators.required, Validators.minLength(this.usernameMinLength)]],
     email: ''
   });
 }

constructor(private fb: NonNullableFormBuilder) { }

The value for the minimum length extracted into a variable also allows us to use it in the template. If we want to change this requirement, we can update the variable’s value in one place. The validators and the error message get updated at once.

Since we don’t want our controls to be nullable, we use the NonNullableFormBuilder class instead of FormBuilder. This makes them all nullable by default. When the “Submit” button is clicked, we invoke the register method and verify the form validity:

register() {
    if (this.registrationForm.valid) {
      console.log(this.registrationForm.value);
    }
  }

If the form is in a valid state, the code will continue and, typically, send the payload to the server. In the demo, we log the form’s value to the console.

Below is the complete component class:

Get hands-on with 1200+ tech skills courses.