Address
Darbhanga, Bihar 846004

 

Template Driven (Form Validation) in Angular

In template.component.html

<form>
    <div class="col-md-4">
        <label class="form-label">First name</label>
        <input type="text" name="firstName" #fName="ngModel" [(ngModel)]="studentObj.firstName" class="form-control"
            required minlength="3">
        <div class="text-danger">
            @if ((fName.touched || fName.dirty) && fName.errors?.['required']) {
            <span>This Is Required</span>
            } @else if ((fName.touched || fName.dirty) && fName.errors?.['minlength']) {
            <span>Min 3 Char Required</span>
            }
        </div>
        <div class="col-12">
            <button class="btn btn-primary mx-2" type="button" (click)="onSubmit()">Submit </button>
        </div>

</form>

In template.component.ts

import { FormsModule } from '@angular/forms';

@Component({
    selector: 'app-template',
    standalone: true,
    imports: [FormsModule],
    templateUrl: './template.component.html',
    styleUrl: './template.component.css'
})

export class TemplateComponent {
    studentObj: any = {
        firstName: '' '',
    }
    formValue: any;
    onSubmit() {
        this.formValue = this.studentObj;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *