Advertisement
fabiobiondi

Angular Reactive FormGroup Validators

Nov 17th, 2020
1,285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
  2. import { AbstractControl, FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
  3.  
  4. @Component({
  5.   selector: 'app-root',
  6.   template: `
  7.     <form [formGroup]="form" (ngSubmit)="save()">
  8.      
  9.       <input type="text" formControlName="username" class="form-control" placeholder="user name">
  10.      
  11.       <div formGroupName="passwords">
  12.         <input type="text" formControlName="password1">  
  13.         <input type="text" formControlName="password2">
  14.       </div>
  15.       1: {{form.get('passwords').get('password1').errors | json }}
  16.       <br>
  17.       2: {{form.get('passwords').get('password2').errors | json }}
  18.       <button [disabled]="form.invalid">save</button>
  19.     </form>
  20.   `,
  21. })
  22. export class AppComponent  {
  23.   form: FormGroup;
  24.   step = 0;
  25.  
  26.   constructor(private fb: FormBuilder) {
  27.     this.form = fb.group({
  28.       username: ['', Validators.required],
  29.       passwords: fb.group(
  30.         {
  31.           password1: ['', [ Validators.required, Validators.minLength(3)]],
  32.           password2: ['', [ Validators.required, Validators.minLength(3)]],
  33.         },
  34.         {
  35.           validator: passwordMatch()
  36.         }
  37.       )
  38.     });
  39.  
  40.   }
  41.  
  42.   save(): void {
  43.     console.log(this.form.value)
  44.   }
  45. }
  46.  
  47.  
  48. function passwordMatch(): any {
  49.   return (group: FormGroup) => {
  50.     const pass1 = group.get('password1');
  51.     const pass2 = group.get('password2');
  52.     if (!pass2.errors && pass1.value === pass2.value) {
  53.       pass2.setErrors(null)
  54.     } else {
  55.       pass2.setErrors({ ...pass2.errors, noMatch: true })
  56.     }
  57.   }
  58. }
  59.  
  60.  
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement