My custom validator does not work, Angular 6, Reactive Forms

1

I am trying to do a custom validation for my form. I have a service that checks in my database if the reference is valid.

Once the reference has been checked, I assign a boolean value to a variable, depending on that value I would like to validate or not the form.

The controller code is:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  dataForm: FormGroup;
  controlref: boolean;


  constructor(private fb: FormBuilder) {

  }

  ngOnInit() {
    this.dataForm = this.fb.group({
      ref: ['', [Validators.required, this.validateRef(this.controlref)]],
    })
  }

  changeControlRef(article: boolean) {
    this.controlref = !this.controlref;
    console.log('aqui',this.controlref)

  }

  validateRef(controlref: boolean) {

    return () => {
      if (controlref) {

        return { 'validRef': true };
      } else {

        return { 'validRef': false };
      }
    }
  }



}

I leave here the STACKBLITZ

// The changeControlRef () function simulates the assignment of my service.

    
asked by Sergio Cano 06.08.2018 в 09:09
source

1 answer

0

The problem is your validateRef method, which creates a closure on the initial value of this.controlRef (which is undefined ):

class Ejemplo {
 
  constructor(value) {
    this.ref=value;
    this.clausura=this.show(this.ref);
  }
 
  show(controlref) {
  //controlref es un valor accesible por la función declarada, pero no
  // está asociado con this.ref
    return () => {
      console.log(controlref);
    }
  }
}

let e= new Ejemplo(true);
e.clausura();
e.ref=false; //esta modificación no afecta a la clausura
e.clausura();

You do not really need that closure, access directly to this.controlref :

  ngOnInit() {
    this.dataForm = this.fb.group({
      ref: ['', [Validators.required, this.validateRef.bind(this)]],
    })
  }

  ...

  validateRef() {
    if (this.controlref) {
      return { 'validRef': true };
    } else {
      return { 'validRef': false };
    }
  }

Running on a Stackblitz

    
answered by 06.08.2018 / 10:13
source