This is a login component built using Material for Angular that is mobile responsive.
login.component.css:
Code:
mat-form-field {
display: block;
}
.u-h-center {
margin-left: auto;
margin-right: auto;
}
.u-mt-3 {
margin-top: 3rem;
}
.u-mw-500 {
max-width: 500px;
}
login.component.html:
HTML Code:
<mat-card class="u-mt-3" [ngClass]="{ 'u-h-center u-mw-500': !isMobile }">
<mat-card-title>Login Form</mat-card-title>
<mat-card-subtitle>Written by dday9</mat-card-subtitle>
<mat-card-content>
<form [formGroup]=form (submit)="login()">
<mat-form-field>
<mat-label>Email</mat-label>
<input matInput type="email" formControlName="email">
<button *ngIf="form?.get('email')?.value" matSuffix mat-icon-button aria-label="Clear" (click)="resetValue('email')">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
<mat-form-field>
<mat-label>Password</mat-label>
<input matInput type="password" formControlName="password">
<button *ngIf="form?.get('password')?.value" matSuffix mat-icon-button aria-label="Clear" (click)="resetValue('password')">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
<a href="#">Forgot your password?</a>
</form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" (click)="login()">Login</button>
<button mat-button [routerLink]="['/register']">Register</button>
</mat-card-actions>
</mat-card>
login.component.ts:
Code:
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, OnDestroy {
form = this.buildForm();
isMobile = false;
private subscriptions: Subscription[] = [];
constructor(private breakpointObserver: BreakpointObserver,
private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.subscriptions.push(this.breakpointObserver.observe([
Breakpoints.XSmall,
Breakpoints.Small,
Breakpoints.Handset
]).subscribe(result => this.isMobile = result.matches));
this.form = this.buildForm();
}
ngOnDestroy(): void {
this.subscriptions.forEach(subscription => subscription.unsubscribe());
}
login(): void {
if (this.form?.invalid) {
this.form?.markAllAsTouched();
return;
}
// TODO: make login call
}
resetValue(fieldControlName: string): void {
this.form?.get(fieldControlName)?.reset(null);
}
private buildForm(): FormGroup {
return this.formBuilder.group({
email: [ null, [ Validators.required, Validators.email ]],
password: [ null, [ Validators.required ]]
});
}
}
Stackblitz Demo: https://stackblitz.com/edit/angular-ivy-jmbp1o