Rachmat Chang
Rachmat Chang

Reputation: 197

Get value from another control in a validator

In there, I want to get value from my HTML code to function in Angular 2, this is my code :

checknewpasswordoldpassword(control: AbstractControl): {[s: string]: boolean}{
    //i want get value from html in here
    return { nospace: true};
}

this is my ogOnInit() :

ngOnInit(){
    this.submitButtonText = 'Accept';
    this.form = this.fb.group({
        'id': [],
        'registerkey':[this.id],
        'username': ['', Validators.compose([Validators.required])],
        'newpassword': ['', Validators.compose([Validators.required,this.checknewpasswordoldpassword])],
        'oldpassword': ['', Validators.compose([Validators.required])]
    });
    this.username = this.form.controls['username'];
    this.registerkey = this.form.controls['registerkey'];
    this.newpassword = this.form.controls['newpassword'];
    this.oldpassword = this.form.controls['oldpassword'];
}

i want to get value newpassword. this is my html code :

<div class="form-group row" [ngClass]="{'has-error': (!oldpassword.valid && oldpassword.touched), 'has-success': (oldpassword.valid && oldpassword.touched)}">
    <label class="col-sm-2 control-label">Old Password</label>
    <div class="col-sm-3">
        <input [formControl]="oldpassword" type="text" class="form-control" placeholder="old password"/>
    </div>
</div>

this is the error :

enter image description here

Upvotes: 2

Views: 3646

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658205

checknewpasswordoldpassword(oldpassword:AbstractControl) => {
   (control: AbstractControl): {[s: string]: boolean}{
       //i want get value from html in here
       let newPass = oldpassword.value
       return { nospace: true};
   }
}
ngOnInit(){
    this.submitButtonText = 'Accept';
    this.form = this.fb.group({
        'id': [],
        'registerkey':[this.id],
        'username': ['', Validators.compose([Validators.required])],
        'newpassword': [''],
        'oldpassword': ['', Validators.compose([Validators.required])]
    });
    this.username = this.form.controls['username'];
    this.registerkey = this.form.controls['registerkey'];
    this.newpassword = this.form.controls['newpassword'];
    this.oldpassword = this.form.controls['oldpassword'];
    this.newpassword.setValidators(Validators.compose([
        Validators.required,
        this.checknewpasswordoldpassword(this.oldpassword)
    ]);
}

Upvotes: 1

Related Questions