ANGULAR Form Template
ANGULAR
Template-driven validation in Angular is accomplished by applying logic to the HTML template using standard HTML validation features and Angular directives.
Angular Form submit with template Example
➔ This example shows how from submit with template works in Angular.
Create a project by ng new tdf-form-validation command.
ng new tdf-form-validation
app.module.ts file
Copy this file content to the target file.
Example
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import{FormsModule} from '@angular/forms'
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Copy the code and try it out practically in your learning environment.
Model product.ts file
Copy this file content to the target file.
Example
export class Product {
id:number;
name:string;
category:string;
price:number;
images:string;
constructor(id?:any,name?:any, category?:any, price?:any,images?:any){
this.id=id;
this.name=name;
this.category=category;
this.price=price;
this.images=images;
}
}
Copy the code and try it out practically in your learning environment.
app.component.ts file
Copy this file content to the target file.
Example
import { Component } from '@angular/core';
import { Product } from './product';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'formvalidation';
products: Product[] = [
new Product(101, "computer", "desktop", 50, "assets/desktop.jpg"),
new Product(102, "laptop", "laptop", 70, "assets/laptop.jpg"),
new Product(103, "soccer Ball", "soccer", 2, "assets/laptop.jpg"),
]
msg: string = "";
p: Product = new Product();
setProduct(pr: any) {
this.p = new Product(pr.id, pr.name, pr.category, pr.price, pr.images);
}
addProduct(id: number) {
let found = this.products.find(element => element.id == id);
if (found == null && id > 0) {
this.products.push(new Product(id, this.p.name, this.p.category, this.p.price, this.p.images));
this.products.sort((a = new Product(), b = new Product()) => a.id - b.id);
this.msg = "Item Added";
} else {
this.msg = "Item Empty or Already Exists";
}
}
removeProduct(id: any) {
const found = this.products.find(element => element.id == id);
let elementIndex = this.products.findIndex((element) => element.id == id)
if (found != null) {
this.products.splice(elementIndex, 1);
this.msg = "Deleted {id=" + (found.id + ", name=" + found.name + "}");
} else {
this.msg = "Item Not Found";
}
// this.products = this.products.filter(function (e) {
// return e.id !== id;
// });
}
updateProduct(id: any, name: any, category: any, price: any, images: any) {
const found = this.products.find(element => element.id == id);
let elementIndex = this.products.findIndex((element) => element.id == id)
if (found != null) {
this.products.splice(elementIndex, 1, new Product(id, name, category, price, images));
this.msg = "Item Updated for index " + (found.id);
} else {
this.msg = "Item Not Found";
}
// this.products = this.products.filter(function (e) {
// return e.id !== id;
// });
// this.products.push(new Product(id, name, category, price,images));
}
resetting() {
this.p = new Product();
this.msg = "";
// this.p.id=0;
// this.p.name="";
// this.p.category="";
// this.p.price=0;
// this.p.images="";
}
}
Copy the code and try it out practically in your learning environment.
Note: put the images in assets folder.
HTML app.component.html File
Copy this file content to the target file.
Example
<div class="container">
<div class="row">
<div class="col-4">
<p>Add Item</p>
<h4 class="p-2 bg-white">{{ msg }}</h4>
<div class="form-froup">
<label>Product ID</label>
<input class="form-control" name="id" #id1="ngModel" [(ngModel)]="p.id" required minlength="3"
maxlength="6" pattern="^[0-9]+$">
<ul class="text-danger list-unstyled" *ngIf="id1.dirty && id1.invalid">
<li *ngIf="id1.errors?.['required']"> Must enter ID</li>
<li *ngIf="id1.errors?.['minlength']"> Must be {{id1.errors?.['minlength'].requiredLength}} chars.</li>
<li *ngIf="id1.errors?.['maxlength']"> Must be {{id1.errors?.['maxlength'].requiredLength}} chars.</li>
<li *ngIf="id1.errors?.['pattern']"> ID can have numbers only.</li>
</ul>
</div>
<div class="form-froup">
<label>Product Name</label>
<input class="form-control" name="name" #name1="ngModel" [(ngModel)]="p.name" required minlength="5"
pattern="^[a-zA-Z0-9 ]+$">
<ul class="text-danger list-unstyled" *ngIf="name1.dirty && name1.invalid">
<li *ngIf="name1.errors?.['required']"> Must enter name</li>
<li *ngIf="name1.errors?.['minlength']"> Must be {{name1.errors?.['minlength'].requiredLength}} chars.</li>
<li *ngIf="name1.errors?.['pattern']"> Name can have letters numbers and spaces.</li>
</ul>
</div>
<div class="form-froup">
<label>Product Category</label>
<input class="form-control" name="category" #category1="ngModel" [(ngModel)]="p.category">
</div>
<div class="form-froup">
<label>Product Price</label>
<input class="form-control" name="price" #price1="ngModel" [(ngModel)]="p.price">
</div>
<div class="form-froup">
<label>Product Image</label>
<input class="form-control" name="images" #images1="ngModel" [(ngModel)]="p.images">
</div>
<!-- <button class="btn btn-primary p-2 m-3" type="submit" [class.disabled]="!contactForm.valid">Submit</button> -->
<button class="btn btn-primary m-3 p-2" (click)="addProduct(id1.value)">Create</button>
<button class="btn btn-primary m-3 p-2" (click)="removeProduct(id1.value)">Remove</button>
<button class="btn btn-primary m-3 p-2"
(click)="updateProduct(id1.value,name1.value,category1.value,price1.value,images1.value)">update</button>
<button type="button" (click)="resetting()" class="btn btn-warning float-right p-2 m-3">Reset</button>
</div>
<div class="col-1">
</div>
<div class="col-6">
<table class="table">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Category</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let p of products" (click)="setProduct(p)">
<th scope="row">{{p.id}}</th>
<td>{{p.name}}</td>
<td>{{p.category}}</td>
<td>{{p.price}}</td>
<td>{{p.images}}</td>
<td><img src="{{p.images}}" height="60px" width="60px" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Copy the code and try it out practically in your learning environment.
HTML index.html File
Copy this file content to the target file.
Example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Formvalidation</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js" integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
Copy the code and try it out practically in your learning environment.
Output
Run project by ng serve in command line (from inside project directory).
program output