Template-Driven 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: Now create the form and add validation in the ‘form-component.component.html’.
<div>
<h1>Template-Driven Form Validation</h1>
<form #myForm="ngForm" (ngSubmit)="submit()">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" [(ngModel)]="user.name" #name="ngModel" required minlength="3">
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
<div *ngIf="name.errors.required">Name is required.</div>
<div *ngIf="name.errors.minlength">Name must be at least 3 characters long.</div>
</div>
</div>
<pre></pre>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" [(ngModel)]="user.email" #email="ngModel" required email>
<div *ngIf="email.invalid && (email.dirty || email.touched)" class="alert alert-danger">
<div *ngIf="email.errors.required">Email is required.</div>
<div *ngIf="email.errors.email">Invalid email format.</div>
</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 and attributes.
import { Component } from '@angular/core';
@Component({
selector: 'app-form-component',
templateUrl: './form-component.component.html',
styleUrls: ['./form-component.component.css']
})
export class FormComponentComponent {
user = { name: '', email: '' }
submit() {
console.log('Form Submitted', this.user);
}
}
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