从验证器中的另一个控件获取值

时间:2016-12-22 08:36:35

标签: angular

在那里,我希望从HTML代码中获取值以在Angular 2中运行,这是我的代码:

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

这是我的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'];
}

我想获得值newpassword。这是我的HTML代码:

<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>

这是错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

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)
    ]);
}
相关问题