We need a material login form, like the one seen below, as a prototyping and learning tool.
Approach
Step 1
Initialize the material module with the needed components:
import { NgModule } from '@angular/core';
import {
MatCardModule,
MatInputModule,
MatButtonModule
} from '@angular/material';
const modules = [
MatCardModule,
MatInputModule,
MatButtonModule
];
@NgModule({
imports: modules,
exports: modules,
})
export class MaterialModule {}
Step 2
Create the login form component:
import { Component, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-login-form',
template: `
<mat-card>
<mat-card-title>Login</mat-card-title>
<mat-card-content>
<form [formGroup]="form" (ngSubmit)="submit()">
<p>
<mat-form-field>
<input type="text" matInput placeholder="Username" formControlName="username">
</mat-form-field>
</p>
<p>
<mat-form-field>
<input type="password" matInput placeholder="Password" formControlName="password">
</mat-form-field>
</p>
<p *ngIf="error" class="loginError">
{{ errorMessage }}
</p>
<p class="button">
<button type="submit" mat-button>Login</button>
</p>
</form>
</mat-card-content>
</mat-card>
`,
styles: [
`
:host {
display: flex;
justify-content: center;
margin: 100px 0px;
}
.mat-form-field {
width: 100%;
min-width: 300px;
}
mat-card-title,
mat-card-content {
display: flex;
justify-content: center;
}
.error {
padding: 16px;
width: 300px;
color: white;
background-color: red;
}
.button {
display: flex;
justify-content: flex-end;
}
`,
],
})
export class LoginFormComponent {
form: FormGroup = new FormGroup({
username: new FormControl(''),
password: new FormControl(''),
});
submit() {
if (this.form.valid) {
this.submitEM.emit(this.form.value);
}
}
@Output() submitEM = new EventEmitter();
}
Step 3
Import the material module, and the login form component, into the app module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { LoginFormComponent } from './login-form.component';
import { MaterialModule } from './material.module';
@NgModule({
imports:[ BrowserModule, ReactiveFormsModule, MaterialModule, BrowserAnimationsModule],
declarations: [ AppComponent, LoginFormComponent ],
bootstrap: [ AppComponent ]})
export class AppModule {}