Build an Angular Material login form
Today we're going to build a login form with Angular Material.
We'll be using a reactive Angular form.
And also be doing input validation to verify that the input we receive is valid. When input is invalid we'll display an error by using mat-error.
Let's get started!
Creating our login Angular Material component
We'll start by using the Angular CLI to generate a login
component.
ng g c login
Then we'll open the login.component.ts
file and add our imports, form and submit function.
import { Component } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { ReactiveFormsModule, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
@Component({
selector: 'app-login',
standalone: true,
imports: [ReactiveFormsModule, MatButtonModule, MatFormFieldModule, MatInputModule],
templateUrl: './login.component.html',
styleUrl: './login.component.scss'
})
export class LoginComponent {
loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required]),
});
submit() {
if (this.loginForm.invalid) {
return;
}
const username = this.loginForm.get('username')?.value;
const password = this.loginForm.get('password')?.value;
// Authenticate with an API or Google Firebase Auth
}
}
We've declared our form group and set up the validators.
Now on to our template's HTML code.
<form class="form flex flex-center" [formGroup]="loginForm">
<h3>Login</h3>
<mat-form-field class="form-field" appearance="outline">
<mat-label>Email</mat-label>
<input type="email" matInput formControlName="email">
@if (loginForm.get('email')?.hasError('required')) {
<mat-error>Email is required</mat-error>
}
@if (loginForm.get('email')?.hasError('email')) {
<mat-error>Invalid email</mat-error>
}
</mat-form-field>
<mat-form-field class="form-field" appearance="outline">
<mat-label>Password</mat-label>
<input type="password" matInput formControlName="password">
@if (loginForm.get('password')?.hasError('required')) {
<mat-error>Password is required</mat-error>
}
</mat-form-field>
<button mat-stroked-button (click)="submit()" [disabled]="loginForm.invalid">LOGIN</button>
</form>
You'll notice that we're using the @if syntax to check for form errors and then using the mat-error to display an error for the email and password validation fields.
And here's the result!
Till next time,
Daniel Kreider