OUTPUT :
- Create angular environment using npm i @angular/cli
- Create an angular folder ng new [folderName]
- Install bootstrap using npm i bootstrap and add the following to your style.css file
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
app.component.html :
- <div class="center">
- <br>
- <mat-toolbar>
- <span class="fill-remaining-space">Reactive Form with Material UI</span>
- </mat-toolbar>
- <div class="container" alignItems='center' justify='center' *ngIf="!post; else forminfo" novalidate>
- <form [formGroup]="formGroup" (ngSubmit)="onSubmit(formGroup.value)" class="form">
- <mat-form-field class="form-element">
- <input matInput placeholder="Enter Email Address" 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">
- <input matInput placeholder="Enter Name" formControlName="name">
- <mat-error *ngIf="!name.valid && name.touched">
- {{ titleAlert }}
- </mat-error>
- </mat-form-field>
- <mat-radio-group aria-label="Select Gender">
- <mat-radio-button value="1">Male</mat-radio-button>
- <mat-radio-button value="2">Female</mat-radio-button>
- </mat-radio-group>
- <mat-form-field class="form-element">
- <input matInput placeholder="Enter Password" formControlName="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'].valid && formGroup.controls['password'].touched">
- {{ getErrorPassword() }}
- </mat-error>
- </mat-form-field>
- <div class="form-element">
- <button mat-raised-button type="submit" class="button" [disabled]="!formGroup.valid">Submit Form</button>
- </div>
- </form>
- </div>
- <ng-template #forminfo>
- <div class="container">
- {{ post | json }}
- </div>
- </ng-template>
- </div>
app.component.ts:
- import { Component } from '@angular/core';
- import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
- import { Observable } from 'rxjs/Observable';
- @Component({
- selector: 'my-app',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- title = 'Material UI Forms';
- formGroup!: FormGroup;
- titleAlert: string = 'Name 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({
- 'email': [null, [Validators.required, Validators.pattern(emailregex)], this.checkInUseEmail],
- 'name': [null, Validators.required],
- 'password': [null, [Validators.required, this.checkPassword]],
- 'gender': ['', '']
- });
- }
- setChangeValidate() {
- this.formGroup.get('validate')?.valueChanges.subscribe(
- (validate) => {
- if (validate == '1') {
- this.formGroup.get('name')?.setValidators([Validators.required]);
- 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: any) {
- let enteredPassword = control.value
- let passwordCheck = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/;
- return (!passwordCheck.test(enteredPassword) && enteredPassword) ? { 'requirements': true } : null;
- }
- checkInUseEmail(control: any) {
- // mimic http database access
- let db = [''];
- return new Observable(observer => {
- setTimeout(() => {
- let result = (db.indexOf(control.value) !== -1) ? { 'alreadyInUse': true } : null;
- observer.next(result);
- observer.complete();
- }, 4000)
- })
- }
- getErrorEmail() {
- return this.formGroup.get('email')?.hasError('required') ? 'Email Address is required' :
- this.formGroup.get('email')?.hasError('pattern') ? 'Not a valid Email address' :
- this.formGroup.get('email')?.hasError('alreadyInUse') ? 'This email Address is already in use' : '';
- }
- getErrorPassword() {
- return this.formGroup.get('password')?.hasError('required') ? 'Password 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: any) {
- this.post = post;
- }
- }
app.component.css :
.fill-remaining-space {
/* This fills the remaining space, by using flexbox.
Every toolbar row uses a flexbox row layout. */
width: fit-content;
font-family:cursive;
}
.mat-toolbar{
width:520px;
}
.container {
padding: 10px;
align-items:'center';
justify-content:'center';
width: fit-content;
}
.form {
min-width: 150px;
max-width: 500px;
width: 100%;
align-items:'center';
justify-content:'center';
}
.form-element {
padding: 5px 0px 25px 2px;
width: 100%;
align-items:'center';
justify-content:'center';
color:darkblue;
font-family:cursive;
}
.button {
width: 100%;
align-items:'center';
justify-content:'center';
}
.mat-radio-button ~ .mat-radio-button {
margin-left: 16px;
align-items:'center';
justify-content:'center';
}
.center{
margin-left: 450px;
}
.mat-toolbar{
color:cyan;
text-align: center;
background-color: darkblue;
}
.mat-raised-button{
color:cyan;
background-color: darkblue;
}
app.module.ts:
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
- import { ReactiveFormsModule } from '@angular/forms';
- import { MaterialModule } from './material.module';
- import { AppComponent } from './app.component';
- @NgModule({
- imports: [
- BrowserModule,
- BrowserAnimationsModule,
- ReactiveFormsModule,
- MaterialModule ],
- declarations: [ AppComponent ],
- bootstrap: [ AppComponent ]
- })
- export class AppModule { }
material.module.ts:
Create a new file material.module.ts and import the following Material UI component
- import { NgModule } from '@angular/core';
- import { CommonModule } from '@angular/common';
- import { MatAutocompleteModule} from '@angular/material/autocomplete';
- import { MatButtonModule} from '@angular/material/button';
- import { MatButtonToggleModule} from '@angular/material/button-toggle';
- import { MatCardModule} from '@angular/material/card';
- import { MatCheckboxModule} from '@angular/material/checkbox';
- import { MatChipsModule} from '@angular/material/chips';
- import { MatDatepickerModule} from '@angular/material/datepicker';
- import { MatDialogModule} from '@angular/material/dialog';
- import { MatExpansionModule} from '@angular/material/expansion';
- import { MatGridListModule} from '@angular/material/grid-list';
- import { MatIconModule} from '@angular/material/icon';
- import { MatInputModule} from '@angular/material/input';
- import { MatListModule} from '@angular/material/list';
- import { MatMenuModule} from '@angular/material/menu';
- import { MatNativeDateModule } from '@angular/material/core';
- import { MatPaginatorModule} from '@angular/material/paginator';
- import { MatProgressBarModule} from '@angular/material/progress-bar';
- import { MatProgressSpinnerModule} from '@angular/material/progress-spinner';
- import { MatRadioModule} from '@angular/material/radio';
- import { MatRippleModule} from '@angular/material/core';
- import { MatSelectModule} from '@angular/material/select';
- import { MatSidenavModule} from '@angular/material/sidenav';
- import { MatSliderModule} from '@angular/material/slider';
- import { MatSlideToggleModule} from '@angular/material/slide-toggle';
- import { MatSnackBarModule} from '@angular/material/snack-bar';
- import { MatSortModule} from '@angular/material/sort';
- import { MatTableModule} from '@angular/material/table';
- import { MatTabsModule} from '@angular/material/tabs';
- import { MatToolbarModule} from '@angular/material/toolbar';
- import { MatTooltipModule} from '@angular/material/tooltip';
- import { MatStepperModule} from '@angular/material/stepper';
- @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 {}
0 Comments