Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 699
MelDsz Avatar asked Dec 08 '22 15:12

MelDsz


1 Answers

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)],
});
like image 73
Titian Cernicova-Dragomir Avatar answered Dec 28 '22 06:12

Titian Cernicova-Dragomir