获取表单控件的名称 [英] Get name of Form Control

查看:24
本文介绍了获取表单控件的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular 的反应形式,我需要将开始日期开始日期"与结束日期结束日期"进行比较,两个控件都在dateLessThan"函数中进行了验证,但问题是我不知道如何要求控制正在评估

I'm working with reactive forms in angular, I need to compare the start date "start date" with the end date "end date", both controls are validated in the "dateLessThan" function, but the problem is that I do not know how to ask for control is evaluating

//Some stuff
public fechaInicio = new FormControl('', [
    Validators.required    
    , this.dateLessThanTo

]);
public fechaFin = new FormControl('', [
    Validators.required     
    , this.dateLessThan
]);



 createForm() {
    this.contratoForm = this.formBuilder.group({    
        fechas: this.formBuilder.group({
            fechaInicio: this.fechaInicio,
            fechaFin: this.fechaFin
        }, { validator: this.dateLessThan('fechaInicio', 'fechaFin') }),          

    });
}

这里我需要知道比较日期的控件名称:

Here I Need to know the name of control for compare dates:

 dateLessThanTo(fieldControl: FormControl) {
    //
    //if (fechaInicio.value > FechaFin.value){
    //      return true;
    //}
    //else{
    //  return false;
    //  }

}

//Some stuff

推荐答案

在你的自定义验证器中,你得到了 formGroup fechas,所以你不需要传递任何来自 TS 代码的参数:

In your custom validator, you get the formGroup fechas, so you do not need to pass any parameters from the TS code:

 createForm() {
    this.contratoForm = this.formBuilder.group({    
        fechas: this.formBuilder.group({
            fechaInicio: this.fechaInicio,
            fechaFin: this.fechaFin
        }, { validator: this.dateLessThanTo }),          

    });
}

并在您的自定义验证器中:

and in your custom validator:

dateLessThanTo(group: FormGroup) {
   if (group.controls.fechaInicio.value > group.controls.fechaFin.value){
     return {notValid: true}
   }
   return null;
}

有效时返回null,无效时设置错误,例如notValid.

You need to return null when valid, and set an error, e.g notValid when it's not.

这篇关于获取表单控件的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆