Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of Form Control

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
like image 763
ararb78 Avatar asked Dec 15 '17 13:12

ararb78


3 Answers

Get the parent group from the control and then compare to the current control:

  dateLessThanTo(control: AbstractControl) { 
    let name = this.getName(control);

    ...
  }

  private getName(control: AbstractControl): string | null {
    let group = <FormGroup>control.parent;

    if (!group) {
      return null;
    }

    let name: string;

    Object.keys(group.controls).forEach(key => {
      let childControl = group.get(key);

      if (childControl !== control) {
        return;
      }

      name = key;
    });

    return name;
  }
like image 106
jcroll Avatar answered Oct 07 '22 02:10

jcroll


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

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

like image 29
AT82 Avatar answered Oct 07 '22 02:10

AT82


in your component you can add a custom validator like this one

static customValidator(control: AbstractControl): { [key: string]: any } {
const controlName = (Object.keys(control.parent.controls).find(key => control.parent.controls[key] === control));
if (control.value === 0) {
  return {key: {error: 'invalid'}};
}
return null; }

in controlName you will have the name of your control.

like image 41
Mariano Calcagno Avatar answered Oct 07 '22 03:10

Mariano Calcagno