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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With