Template Form
Modules
- ngForm
- ngModel
- ngModelGroup
Disable the button if the formgroup is not valid
<form (ngSubmit)="save()" #signupForm="ngForm">
<button type="submit" [disabled]="!signupForm.valid">
Save
</button>
</form>
Typical Template Form
student.html
<form novalidate (ngSubmit)="save()" [formGroup]="customerForm">
<div [ngClass]="{'hasError':firstNameVar.touched && !firstNameVar.Valid}">
<input type="text" name="fName" required
[(ngModel)]="student.firstName"
#firstNameVar = "ngModel" />
<span *ngIf="(firstNameVar.touched || firstNameVar.dirty) && firstNameVar.errors">
<span *ngIf="firstNameVar.errors.required">
message
</span>
<span *ngIf="firstNameVar.errors.minlength">
message
</span>
<span *ngIf="firstNameVar.errors.pattern">
message
</span>
</span>
<button type="submit" [disabled]="!signupForm.valid">Save</button>
</div>
</form>
We use "novalidate" attribute to tell the browser not to perform its validation rather let angular do validation for us.
"#firstNameVar" template reference method is use to display valid error messages.
this "firstNameVar.errors" collection has all the validation messages