Search code examples
angularangular-reactive-formsangular-forms

Password Confirm Reactive Forms Angular 4


I have a problem regarding my password and confirm password in my angular app. I'm using reactive forms and the error says "supplied parameters do not match any signature on call target"

ngOnInit() {
      this.form = this.formBuilder.group({
        name: [null, [Validators.required, Validators.minLength(3)]],
        email: [null, [Validators.required, Validators.email]],
        password: [null, Validators.required],
        confirm_password: [null, Validators.required],
      }, {validator: this.passwordConfirming('password', 'confirm_password')});

}
  passwordConfirming(c: AbstractControl): { invalid: boolean } {
    if (c.get('password').value !== c.get('confirm_password').value) {
        return {invalid: true};
    }
  }

html

<div class="form-inline">       
    <label class="col-md-4">Password</label>
    <input class="col-md-8" type="password" class="form-control" id="password" formControlName="password">
    <span class="text-muted" *ngIf="!form.controls['password'].valid && form.controls['password']?.touched"> Password is required</span>
 </div>
 <div class="form-inline">       
    <label class="col-md-4">Confirm Password</label>
    <input class="col-md-8" type="password" class="form-control" id="confirm_password" formControlName="confirm_password">

 </div>

Solution

  • Declare your passwordConfirming outside component class as function and then call it for example:

    import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
    import { Component, OnInit, ViewChild } from '@angular/core';
    
    function passwordConfirming(c: AbstractControl): any {
        if(!c.parent || !c) return;
        const pwd = c.parent.get('password');
        const cpwd = c.parent.get('confirm_password');
    
        if(!pwd || !cpwd) return ;
        if (pwd.value !== cpwd.value) {
            return { invalid: true };
        }
    }
    
    @Component({
        templateUrl: './my.component.html',
        styleUrls: ['./my.component.scss']
    })
    export class MyComponent implements OnInit {
        form: FormGroup;
        get cpwd() {
            return this.form.get('confirm_password');
        }
        constructor(private formBuilder: FormBuilder) {}
    
        ngOnInit() {
            this.form = this.formBuilder.group({
                name: [null, [Validators.required, Validators.minLength(3)]],
                email: [null, [Validators.required, Validators.email]],
                password: [null, Validators.required],
                confirm_password: [null, [Validators.required, passwordConfirming]]
            });
        }    
    }
    

    HTML Code:

    <span *ngIf="cpwd.hasError('invalid')"> Invalid Password </span>