Angular Reactive Form Using Material UI

 OUTPUT :

  1.  Create angular environment using npm i @angular/cli
  2.  Create an angular folder ng new [folderName]
  3.  Install bootstrap using npm i bootstrap and add the following to your style.css file
DOWNLOAD COMPLETE PROJECT

@import "~@angular/material/prebuilt-themes/indigo-pink.css";


app.component.html :


  1. <div class="center">
  2.   <br>
  3.   <mat-toolbar>
  4.     <span class="fill-remaining-space">Reactive Form with Material UI</span>
  5.   </mat-toolbar>
  6.   <div class="container" alignItems='center' justify='center' *ngIf="!post; else forminfo" novalidate>
  7.     <form [formGroup]="formGroup" (ngSubmit)="onSubmit(formGroup.value)" class="form">
  8.       <mat-form-field class="form-element">
  9.         <input matInput placeholder="Enter Email Address" formControlName="email">
  10.         <mat-error *ngIf="!formGroup.controls['email'].valid && formGroup.controls['email'].touched">
  11.           {{ getErrorEmail() }}
  12.         </mat-error>
  13.       </mat-form-field>
  14.       <mat-form-field class="form-element">
  15.         <input matInput placeholder="Enter Name" formControlName="name">
  16.         <mat-error *ngIf="!name.valid && name.touched">
  17.           {{ titleAlert }}
  18.         </mat-error>
  19.       </mat-form-field>
  20.       <mat-radio-group aria-label="Select Gender">
  21.         <mat-radio-button value="1">Male</mat-radio-button>
  22.         <mat-radio-button value="2">Female</mat-radio-button>
  23.       </mat-radio-group>
  24.       <mat-form-field class="form-element">
  25.         <input matInput placeholder="Enter Password" formControlName="password">
  26.         <mat-hint>Choose a password of at least eight characters, one uppercase letter and one number</mat-hint>
  27.         <mat-error *ngIf="!formGroup.controls['password'].valid && formGroup.controls['password'].touched">
  28.           {{ getErrorPassword() }}
  29.         </mat-error>
  30.       </mat-form-field>
  31.       <div class="form-element">
  32.         <button mat-raised-button type="submit" class="button" [disabled]="!formGroup.valid">Submit Form</button>
  33.       </div>
  34.     </form>
  35.   </div>
  36.   <ng-template #forminfo>
  37.     <div class="container">
  38.       {{ post | json }}
  39.     </div>
  40.   </ng-template>
  41. </div>


app.component.ts:


  1. import { Component } from '@angular/core';
  2. import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
  3. import { Observable } from 'rxjs/Observable';

  4. @Component({
  5.   selector: 'my-app',
  6.   templateUrl: './app.component.html',
  7.   styleUrls: ['./app.component.css']
  8. })
  9. export class AppComponent {
  10.   title = 'Material UI Forms';
  11.   formGroup!: FormGroup;
  12.   titleAlert: string = 'Name  is required';
  13.   post: any = '';

  14.   constructor(private formBuilder: FormBuilder) { }

  15.   ngOnInit() {
  16.     this.createForm();
  17.     this.setChangeValidate()
  18.   }

  19.   createForm() {
  20.     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,}))$/
  21.     this.formGroup = this.formBuilder.group({
  22.       'email': [null, [Validators.required, Validators.pattern(emailregex)], this.checkInUseEmail],
  23.       'name': [null, Validators.required],
  24.       'password': [null, [Validators.required, this.checkPassword]],
  25.       'gender': ['', '']
  26.     });
  27.   }

  28.   setChangeValidate() {
  29.     this.formGroup.get('validate')?.valueChanges.subscribe(
  30.       (validate) => {
  31.         if (validate == '1') {
  32.           this.formGroup.get('name')?.setValidators([Validators.required]);
  33.           this.titleAlert = "You need to specify at least 3 characters";
  34.         } else {
  35.           this.formGroup.get('name')?.setValidators(Validators.required);
  36.         }
  37.         this.formGroup.get('name')?.updateValueAndValidity();
  38.       }
  39.     )
  40.   }

  41.   get name() {
  42.     return this.formGroup.get('name') as FormControl
  43.   }

  44.   checkPassword(control: any) {
  45.     let enteredPassword = control.value
  46.     let passwordCheck = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/;
  47.     return (!passwordCheck.test(enteredPassword) && enteredPassword) ? { 'requirements': true } : null;
  48.   }

  49.   checkInUseEmail(control: any) {
  50.     // mimic http database access
  51.     let db = [''];
  52.     return new Observable(observer => {
  53.       setTimeout(() => {
  54.         let result = (db.indexOf(control.value) !== -1) ? { 'alreadyInUse': true } : null;
  55.         observer.next(result);
  56.         observer.complete();
  57.       }, 4000)
  58.     })
  59.   }

  60.   getErrorEmail() {
  61.     return this.formGroup.get('email')?.hasError('required') ? 'Email Address is required' :
  62.       this.formGroup.get('email')?.hasError('pattern') ? 'Not a valid Email address' :
  63.         this.formGroup.get('email')?.hasError('alreadyInUse') ? 'This email Address is already in use' : '';
  64.   }

  65.   getErrorPassword() {
  66.     return this.formGroup.get('password')?.hasError('required') ? 'Password is required (at least eight characters, one uppercase letter and one number)' :
  67.       this.formGroup.get('password')?.hasError('requirements') ? 'Password needs to be at least eight characters, one uppercase letter and one number' : '';
  68.   }

  69.   onSubmit(post: any) {
  70.     this.post = post;
  71.   }

  72. }


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:


  1. import { NgModule } from '@angular/core';
  2. import { BrowserModule } from '@angular/platform-browser';
  3. import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
  4. import { ReactiveFormsModule } from '@angular/forms';

  5. import { MaterialModule } from './material.module';
  6. import { AppComponent } from './app.component';

  7. @NgModule({
  8.   imports:      [
  9.     BrowserModule,
  10.     BrowserAnimationsModule,
  11.     ReactiveFormsModule,
  12.     MaterialModule ],
  13.   declarations: [ AppComponent ],
  14.   bootstrap:    [ AppComponent ]
  15. })
  16. export class AppModule { }


material.module.ts:

Create a new file material.module.ts and import the following Material UI component

  1. import { NgModule } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { MatAutocompleteModule} from '@angular/material/autocomplete';
  4. import { MatButtonModule} from '@angular/material/button';
  5. import { MatButtonToggleModule} from '@angular/material/button-toggle';
  6. import { MatCardModule} from '@angular/material/card';
  7. import { MatCheckboxModule} from '@angular/material/checkbox';
  8. import { MatChipsModule} from '@angular/material/chips';
  9. import { MatDatepickerModule} from '@angular/material/datepicker';
  10. import { MatDialogModule} from '@angular/material/dialog';
  11. import { MatExpansionModule} from '@angular/material/expansion';
  12. import { MatGridListModule} from '@angular/material/grid-list';
  13. import { MatIconModule} from '@angular/material/icon';
  14. import { MatInputModule} from '@angular/material/input';
  15. import { MatListModule} from '@angular/material/list';
  16. import { MatMenuModule} from '@angular/material/menu';
  17. import { MatNativeDateModule } from '@angular/material/core';
  18. import { MatPaginatorModule} from '@angular/material/paginator';
  19. import { MatProgressBarModule} from '@angular/material/progress-bar';
  20. import { MatProgressSpinnerModule} from '@angular/material/progress-spinner';
  21. import { MatRadioModule} from '@angular/material/radio';
  22. import { MatRippleModule} from '@angular/material/core';
  23. import { MatSelectModule} from '@angular/material/select';
  24. import { MatSidenavModule} from '@angular/material/sidenav';
  25. import { MatSliderModule} from '@angular/material/slider';
  26. import { MatSlideToggleModule} from '@angular/material/slide-toggle';
  27. import { MatSnackBarModule} from '@angular/material/snack-bar';
  28. import { MatSortModule} from '@angular/material/sort';
  29. import { MatTableModule} from '@angular/material/table';
  30. import { MatTabsModule} from '@angular/material/tabs';
  31. import { MatToolbarModule} from '@angular/material/toolbar';
  32. import { MatTooltipModule} from '@angular/material/tooltip';
  33. import { MatStepperModule} from '@angular/material/stepper';

  34. @NgModule({
  35.   imports: [
  36.     MatAutocompleteModule,MatButtonModule,MatButtonToggleModule,MatCardModule,MatCheckboxModule,MatChipsModule,
  37.     MatDatepickerModule,MatDialogModule,MatExpansionModule,MatGridListModule,MatIconModule,MatInputModule,
  38.     MatListModule,MatMenuModule,MatNativeDateModule,MatPaginatorModule,MatProgressBarModule,MatProgressSpinnerModule,
  39.     MatRadioModule,MatRippleModule,MatSelectModule,MatSidenavModule,MatSliderModule,MatSlideToggleModule,MatSnackBarModule,
  40.     MatSortModule,MatTableModule,MatTabsModule,MatToolbarModule,MatTooltipModule,MatStepperModule,
  41.   ],
  42.   exports: [
  43.     MatAutocompleteModule,
  44.     MatButtonModule,
  45.     MatButtonToggleModule,
  46.     MatCardModule,
  47.     MatCheckboxModule,
  48.     MatChipsModule,
  49.     MatDatepickerModule,
  50.     MatDialogModule,
  51.     MatExpansionModule,
  52.     MatGridListModule,
  53.     MatIconModule,
  54.     MatInputModule,
  55.     MatListModule,
  56.     MatMenuModule,
  57.     MatNativeDateModule,
  58.     MatPaginatorModule,
  59.     MatProgressBarModule,
  60.     MatProgressSpinnerModule,
  61.     MatRadioModule,
  62.      MatRippleModule,
  63.     MatSelectModule,
  64.     MatSidenavModule,
  65.     MatSliderModule,
  66.     MatSlideToggleModule,
  67.     MatSnackBarModule,
  68.     MatSortModule,
  69.     MatTableModule,
  70.     MatTabsModule,
  71.     MatToolbarModule,
  72.     MatTooltipModule,
  73.     MatStepperModule,
  74.   ]    
  75. })

  76. export class MaterialModule {}

Post a Comment

0 Comments