...

/

Creating Elegant Reactive Forms

Creating Elegant Reactive Forms

Learn how to reactively validate form controls and create a custom validator in Angular.

We will learn how to create Angular forms using an Angular service. The Angular forms library exposes a service called FormBuilder that we can use to simplify form creation. We will learn how to use it by converting the form we created in the product create component:

  1. Open the product-create.component.ts file and import the FormBuilder artifact from the @angular/forms npm package:

import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
Importing FormBuilder
  1. Inject FormBuilder in the constructor of the ProductCreateComponent class:

constructor(private productsService: ProductsService, private builder: FormBuilder) {}
Injecting FormBuilder in the constructor
  1. Convert the productForm property as follows:

Press + to interact
productForm: FormGroup<{
name: FormControl<string>,
price: FormControl<number | undefined>
}> | undefined;
  1. Create the following buildForm method:

Press + to interact
private buildForm() {
this.productForm = this.builder.nonNullable.group({
name: this.builder.nonNullable.control(''),
price: this.builder.nonNullable.control<number | undefined>(undefined, {})
});
}

We use the group method of the FormBuilder service to group form controls together. We also use its control method to create the form controls. Notice that we also use the nonNullable property to indicate that the form ...