Angular Material Form in Angular 8
Angular Material Modules
App.Component.HTML Code
App.Component.ts Code
v Reactive forms are
better than template form.
v Reactive forms are
more scalable, reusable, and testable.
vI n these forms model
which is created under app.module.ts file is responsible
to handle all the user interaction and validation.
No any data Binding
done.
v Mostly code is in
component side.
v
vPrerequisite
vNeed to import ReactiveFormModule under app.module.ts file
Angular Material Modules
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
MatAutocompleteModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
MatStepperModule,
} from '@angular/material';
@NgModule({
imports: [
MatAutocompleteModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
MatStepperModule,
],
exports: [
MatAutocompleteModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
MatStepperModule,
]
})
export class MaterialModule {}
<div> Welcome to {{ title }} app </div>
<hr>
<mat-toolbar color="primary">
<span class="fill-remaining-space"> Reactive Form with Material</span>
</mat-toolbar>
<div class="container" *ngIf="!post; else forminfo" validate>
<form [formGroup]="formGroup" (ngSubmit)="onSubmit(formGroup.value)" class="form">
<mat-form-field class="form-element">
<input matInput placeholder="Name" formControlName="name">
<mat-error *ngIf="!name.valid && name.touched">
"Name is Required"
</mat-error>
</mat-form-field>
<mat-form-field class="form-element">
<mat-label>Date Of birth</mat-label>
<input matInput [matDatepicker]="picker" formControlName="DOB">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<mat-form-field class="form-element">
<input matInput placeholder="Emailaddress" formControlName="email">
<mat-error *ngIf="!formGroup.controls['email'].valid && formGroup.controls['email'].touched">
{{ getErrorEmail() }}
</mat-error>
</mat-form-field>
<mat-form-field class="form-element">
<textarea matInput placeholder="Description" matTextareaAutosize matAutosizeMinRows="2" matAutosizeMaxRows="5" formControlName="description"></textarea>
<mat-error *ngIf="!formGroup.controls['description'].valid && formGroup.controls['description'].touched">
Required field, must be between 5 and 10 characters.
</mat-error>
</mat-form-field>
<mat-form-field class="form-element">
<input matInput placeholder="password" formControlName="password" type="password">
<mat-hint>Choose a password of at least eight characters, one uppercase letter and one number</mat-hint>
<mat-error *ngIf="formGroup.controls['password'].invalid && formGroup.controls['password'].touched">
{{ getErrorPassword() }}
</mat-error>
</mat-form-field>
<div class="form-element">
<mat-checkbox formControlName="validate" value="1">Name min. 3 characters</mat-checkbox>
</div>
<div class="form-element">
<button mat-raised-button color="primary" type="submit" class="button" [disabled]="formGroup.invalid">Submit Form</button>
</div>
</form>
</div>
<ng-template #forminfo>
<div class="container">
{{ post | json }}
</div>
</ng-template>
App.Component.ts Code
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title:string = "The DotNet Office";
formGroup: FormGroup;
titleAlert: string = 'This field is required';
post: any = '';
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.createForm();
this.setChangeValidate()
}
createForm() {
let emailregex: RegExp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
this.formGroup = this.formBuilder.group({
'name': [null, Validators.required],
'email': [null, [Validators.required, Validators.pattern(emailregex)]],
'DOB' :'',
'password': [null, [Validators.required, this.checkPassword]],
'description': [null, [Validators.required, Validators.minLength(5), Validators.maxLength(10)]],
'validate':''
});
}
setChangeValidate() {
this.formGroup.get('validate').valueChanges.subscribe(
(validate) => {
if (validate == '1') {
this.formGroup.get('name').setValidators([Validators.required, Validators.minLength(3)]);
this.titleAlert = "You need to specify at least 3 characters";
} else {
this.formGroup.get('name').setValidators(Validators.required);
}
this.formGroup.get('name').updateValueAndValidity();
}
)
}
get name() {
return this.formGroup.get('name') as FormControl
}
checkPassword(control) {
let enteredPassword = control.value
let passwordCheck = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/;
return (!passwordCheck.test(enteredPassword) && enteredPassword) ? { 'requirements': true } : null;
}
getErrorEmail() {
return this.formGroup.get('email').hasError('required') ? 'Field is required' :
this.formGroup.get('email').hasError('pattern') ? 'Not a valid emailaddress' : '';
}
getErrorPassword() {
return this.formGroup.get('password').hasError('required') ? 'Field is required (at least eight characters, one uppercase letter and one number)' :
this.formGroup.get('password').hasError('requirements') ? 'Password needs to be at least eight characters, one uppercase letter and one number' : '';
}
onSubmit(post) {
this.post = post;
}
}
EmoticonEmoticon