Friday, November 3, 2023

Angular Forms Sample Example -Template Driven Form

Create a Component

ng g c tdf --flat











.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-tdf',
  templateUrl: './tdf.component.html',
  styleUrls: ['./tdf.component.css']
})
export class TdfComponent  implements OnInit{
  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }
  firstname:string | undefined;
  lastname:string | undefined;
  info:string | undefined;

 register(usermodel1: { valid: any; })
 {
   if(usermodel1.valid)
   this.info=this.firstname+":"+this.lastname;
 }
}


.html Changes

<form #usermodel="ngForm">
    <div style="font-size:x-large;margin:20px">
    firstname:<input [(ngModel)]="firstname" name="firstname" required>
    <span *ngIf="usermodel.controls['firstname'].invalid">
        enter firstname
    </span>
    <br>
    lastname:<input [(ngModel)]="lastname" name="lastname" required>
    <span *ngIf="usermodel.controls['lastname'].invalid && usermodel.controls['lastname'].touched">
        enter lastname
    </span>
    <br>
    <input type="button" value="register" (click)="register(usermodel)">
    <br>
    {{info}}
    </div>
  </form>


Output

















MDF vs TDF:
-----------
1.MDF will apply validations to model props with in component class
  TDF  "     "       "       to control with in template

2.MDF will provide programming flexibility
  [like dynamic controls creation and validations can be verified in router guard]

 TDF will not provide programming flexibility

3.MDF makes validations unit testing easy
  TDF doesn't provide validations unit testing easy

4.MDF is not developer friendly
  TDF is developer friendly


No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...