Sample Code: Angular Typed Reactive Form with Child Components & Validations

May 25, 2023
Cover Image

The problem: in Angular, how do you break up a form into child components using @ViewChild() and still get validation to work?

When you're developing an application that has forms with a lot of data, it can get a little bit messy and repetitive. Specifically, I'm thinking about the display of validation messages and handling logic for dropdown lists (aka. control (child component)

Screenshot of the sample application

This is a typed reactive form and all the form properties are created using the FormBuilder's nonNullable controls group. This also defines all the validation rules for those fields.

theForm = this.fb.nonNullable.group({
  firstName: ['', Validators.required],
  lastName: ['', Validators.required],
  email: ['', {
    validators: [Validators.required, Validators.email]
  }],
  status: ['', Validators.required],
  leastFavoriteNumber: this.fb.nonNullable.control<number>(0, {
    validators: [Validators.required,
    Validators.pattern('^-?[0-9]+(.[0-9]*)?$')]
  }),
  favoriteNumber: ['', {
    validators: [Validators.required,
    Validators.pattern('^-?[0-9]+(.[0-9]*)?$')]
  }],
  textbox1: ['', Validators.required],
  textbox2: ['', Validators.required],
  combobox1: ['', Validators.required],
});

Once this is defined, we can do type-safe operations against the form fields using the patchValue() method for setting values.

Summary

In this first article, I just wanted to publish the sample code and give you a quick look at the application. The sample application is running at this link and the sample code is published to GitHub. In future articles, I'll walk you through the implementation for the controls.

I hope this helps.

-Ben

Categories: angular
Tags: angular