Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password comparison directive @input is always undefined in angular Template driven form

Tags:

angular

Hi I'm trying to create a angular directive to compare password and confirm password I tried many example shown on net but none seems to work ,the @input value is always undefined in validate function,where would i be going wrong

Below is my code for Template

<div>
  <h1>Add user</h1>
  <form #f="ngForm" novalidate>
  
  <div>
    <label>Password</label>
    <input type="password" name="password" [ngModel]="user.password" 
      required #password="ngModel">
    <small [hidden]="password.valid || (password.pristine &&    
      !f.submitted)">
      Password is required
    </small>
 </div>
 <div>
    <label>Retype password</label>
    <input type="password" name="confirmPassword"    
      [ngModel]="user.confirmPassword"
      required compare="password" #confirmPassword="ngModel">
    <small [hidden]="confirmPassword.valid ||  
      (confirmPassword.pristine && !f.submitted)">
      Password mismatch
    </small>
 </div>
  </form>
 </div>

and the directive code is as follows

import { Directive, Input, OnInit } from '@angular/core';
import {NG_VALIDATORS,AbstractControl,ValidationErrors,Validator} from '@angular/forms'
@Directive({
  selector: '[compare]',
  providers:[{provide:NG_VALIDATORS,useClass:ValidateEqualDirective,multi:true}]
})
export class ValidateEqualDirective implements Validator,OnInit {
  @Input('compare') controlToCompare;
  public controlCompate
  constructor() { }

  ngOnInit(){
    console.log(this.controlToCompare)
  }
  validate(val:AbstractControl):ValidationErrors|null{

    console.log(this.controlToCompare);
    return null;
  }

}
like image 581
Swarup Chavan Avatar asked Dec 14 '25 14:12

Swarup Chavan


1 Answers

It prints undefined because you told Angular to create a new ValidateEqualDirective instance for validator through useClass:

providers:[{provide:NG_VALIDATORS, useClass:ValidateEqualDirective
                                   ^^^^

It means you have two instances of your class: first one is tied to html structure and second one was create for validation.

You should be using the same directive instance instead:

providers:[{provide:NG_VALIDATORS, useExisting: ValidateEqualDirective
                                  ^^^^^^^^^^^^^^^
                             reuse current directive instance
like image 125
yurzui Avatar answered Dec 16 '25 22:12

yurzui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!