Hello Devs,
In this tutorial, we are going to see example of template-driven form validation in angular 10.
Angular 10 provide forms and they provide way to handle user input using ngModel, ngSubmit.
Follow this step by step guide given below:
Install Angular App
ng new my-new-app
Import FormsModule
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Form with ngModel
src/app/app.component.html
<h1>Template Driven Forms Validation in Angular 10 Example - Rathorji.in</h1>
<form #contactForm="ngForm" (ngSubmit)="submit(contactForm.value)">
<div class="form-group">
<label for="firstName">First Name</label>
<input required minlength="3" maxlength="10" ngModel name="firstName" type="text" #firstName="ngModel" class="form-control" id="firstName">
<div class="alert alert-danger" *ngIf="firstName.touched && !firstName.valid">
<div *ngIf="firstName.errors.required">First Name is required.</div>
<div *ngIf="firstName.errors.minlength">First Name is minimum {{ firstName.errors.minlength.requiredLength }} character.</div>
<div *ngIf="firstName.errors.maxlength">First Name is maximum 10 character.</div>
</div>
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input required ngModel name="lastName" type="text" #lastName="ngModel" class="form-control" id="lastName">
<div class="alert alert-danger" *ngIf="lastName.touched && !lastName.valid">
Last Name is required.
</div>
</div>
<div class="form-group">
<label for="comment">Comment</label>
<textarea required ngModel #comment="ngModel" name="comment" id="comment" cols="30" rows="10" class="form-control"></textarea>
<div class="alert alert-danger" *ngIf="comment.touched && !firstName.valid">
Comment is required.
</div>
</div>
<button class="btn btn-primary" type="submit" [class.disabled]="!contactForm.valid">Submit</button>
</form>
updated Ts File
src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
submit(form){
var firstName = form.firstName;
console.log(firstName);
var lastName = form.lastName;
console.log(lastName);
var comment = form.comment;
console.log(comment);
}
}
Run this command:
ng serve
I hope this example helps you.