Reactive Form-Validation
Example:
Step 1: Create an Angular project using Angular CLI.
ng new angular-forms
Step 2: Create a new component message
ng g c form-component
Step 3: Create the form and add validation in the ‘form-component.component.html’.
<div>
<h1>Reactive Form Validation</h1>
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" formControlName="name">
<div *ngIf="myForm.get('name').hasError('required') && myForm.get('name').touched" class="alert alert-danger">
Name is required.
</div>
<div *ngIf="myForm.get('name').hasError('minlength') && myForm.get('name').touched" class="alert alert-danger">
Name must be at least 3 characters long.
</div>
</div>
<pre></pre>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email">
<div *ngIf="myForm.get('email').hasError('required') && myForm.get('email').touched" class="alert alert-danger">
Email is required.
</div>
<div *ngIf="myForm.get('email').hasError('email') && myForm.get('email').touched" class="alert alert-danger">
Invalid email format.
</div>
</div>
<pre></pre>
<button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
</div>
Step 4: Edit the 'form-component.component.ts' to define the function, attributes and validations.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-form-component',
templateUrl: './form-component.component.html',
styleUrls: ['./form-component.component.css']
})
export class FormComponentComponent {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.myForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.minLength(3)]],
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit() {
if (this.myForm.valid) {
console.log('Form submitted with data:', this.myForm.value);
}
}
}
Step 5: Add CSS to ‘form-component.component.css’ for better styling.
div {
text-align: center;
}
label {
text-align: left;
}
Step 6: Add the ‘<app-form-component></app-form-component>’ to the ‘app.component.html’ to include the ‘Form-Component’ in the main application. Also, add the FormsModule in ‘app.module.ts’.
<app-form-component></app-form-component>
Step 7: Now run or compile the application.
ng serve
You will see the result on http://localhost:4200