We can create a form in Angular through form tag of HTML and Angular allow us to add additional control the form through its new directive like ngForm, ngModel, and ngModelGroup features. Angular allows us to create a form in two different approaches and each had its own an Angular Module as
1. Template drive form (FormsModule)
2. Reactive form (ReactiveFormsModule)
Note The both type of the form we have common building blocks as FormControl, FormGroup, and FormArray.
In this an example, we will walk through
- How to set up your forms
- How to use different Data binding in an Angular Form
- Form validation, and styling.
- Learning the ngModelGroup Directive
Angular allows us to use ngModel in two different data binding
- We can use one-way data binding through
<input type=”email”name=”email”class=”form-control” ngModel>
- We can use two-way data binding [(ngModel)] called a banana in the box structure.
Applying style to Angular Form
When we are using a form in an Angular, Angular will add number class to the form, as
- isTouched (Check form element is touched or not)- ng-untouched or ng-touched.
- is value change (Check the form element value change or not)- ng-pristine ng-dirty.
- is Invalide (Check the input value type or not with the use of required attribute) – ng-valid invalid
In this example, we apply the CSS style to input text through a form element class provided by an Angular. We can use an Angular ng-valid class to apply the CSS style to the input of the form and we can apply the style to the input text of firstName with required attribute through an Angular ng-invalid class.
Add the following code in app.component.html
Add the following code in app.component.ts file
The ngModelGroup, we can use this directive if we like to create a sub-group within a form. This can come in handy if you want to validate a sub-group of your form separately from the rest of your form, or if some values in your domain model make more sense to consume together in a nested object.
In this an example, we will make a form with an Angular directive ngForm, ngModel, and ngModelGroup.
Note: We have to register FormsModule module in app.module.ts from ‘@angular/forms’;
Step 1: Add the code for form app.component.html
Step 2: Add the code in app.component.ts