Here is the code for validating form (Used email build in validator as per my requirement)
Login.Component.html
<form id="loginForm" #validform="ngForm" (ngSubmit)="onSubmit(validform)">
<div class="example-container">
<mat-form-field>
<input matInput placeholder="UserName" [formControl]="userName" autofocus>
<mat-error *ngIf="userName.hasError('email') && !userName.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf="userName.hasError('required')">
Email is
<strong>required</strong>
</mat-error>
<br>
</mat-form-field>
<mat-form-field>
<input matInput type="password" placeholder="Password" [formControl]="password">
<mat-error *ngIf="password.hasError('required')">
Password is
<strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<button type="submit" class="btn btn-success btn-block" [disabled]="userName.hasError('email') || password.hasError('required')"
id="login_btn">Login</button>
</form>
Login.Component.ts
import { Component,OnInit, OnChanges, Injectable } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators,NgForm, NgModel } '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'
]
})
export class LoginComponent implements OnInit {
/* validate form */
validform;
userName : any;
password : any;
constructor(){ }
ngOnInit(){
this.buildForm();
}
buildForm(){
this.userName = new FormControl("", Validators.compose([
Validators.required,
Validators.email,
])),
this.password = new FormControl('', [
Validators.required,
])}
onSubmit = function(validform: NgForm){
//Call the login api with validForm Data
}
}
Hope this will help.
requiredattribute of HTML