In previous we have learned, the template drives forms, in a template-driven from where most of our logic, validation, controls are in template or HTML form. We are applying ngModel and other an Angular directive in template and template drive form is suitable for building the simple form with basic validation(required, minlength, maxlength).
Whereas in case of modal driven (Reactive form): forms, all the control and logic validation of form are defined in your component typescript file. With the model-driven approach, we create form from the instance of FormGroup and the FormBuilder instance allows us to specify form controls and the various validations on the input element of the form in the component. The model drive form is the best choice for creating a complex form, it provides the developer with more control on the form.
In this example, we are learning
- How to build a reactive form with custom validation
- Apply select form element value from external sources.
- Displaying custom error message for each form element error related to validation.
We will make simple reactive form example, we have to follow these step to complete our task.
Step 1: Define reactiveForm module in app.module.ts file
Step 2: Define Form validation in app.component.ts
We will define the form model on from an instance of FormGroup and we will uses form validation from FormBuilder instance. We have to import FormGroup and FormBuilder provider from ‘@angular/form’.
We are defining separate error message for each element validation by define property element in the component and assigning the error message through method called initializeErrorMessages. Add the following code in app.component.ts file.
We can assign the value of the form select element department option value from the external data in file app/data /mockDepartment.ts
In app/data/mockDepartment.ts we have to define the list of department name to array element TamoDepartment
Step 3: Define form in app.component.html
Note: We have to assign form name (formTamo) to an Angular directive [fromGroup] and we are also assigning department select element list value from external data.