Search code examples
javascriptangulartypescriptform-control

Angular 4: using component variables inside custom validator functions


ngOnInit(): void {

this.formBuilder.group({
          nameFormCtrl: ['', this.validateName],
          });

}

validateName(c: FormControl) {
    return c.value === this.name ? null : {
      validateName: {
        valid: false
      }
    };
  }

Here this.name should refer to the component, instead, it refers to undefined


Solution

  • Class methods do not have this bound to the current instance, they are dependent on the caller to pass the appropriate this to the function when calling, just like any other function in Javascript

    You can use an arrow function which captures this from declaration context, or explicitly bind this using bind:

    this.formBuilder.group({
          nameFormCtrl: ['', c=> this.validateName(c)],
          // OR
          nameFormCtrl: ['', this.validateName.bind(this)],
    });