Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - validator custom function this is undefined

I'm building an app with component FormComponent. inside I'm using reactive forms module from angular core and create a custom validator. the function is calling another function by using this - as I supposed it will refer to the FormComponent, but it refers to be 'undefined' (?)

The code in onInit defines the FormGroup and FormControl and outside of it defines the functions

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {

  formInsurance:FormGroup;
  private id:FormControl;


  constructor(){}


  ngOnInit() {

    this.id = new FormControl('',[
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10),
      Validators.pattern('^[0-9]+(-[0-9]+)+$|^[0-9]+$'),
      this.foo
    ]);


    this.formInsurance = new FormGroup({
      id:this.id      
    })


  }


  foo(control:FormControl){
  this.boo();
  if(control.value){
    return {
      objToReturn: {
          returned: name
      }
    };
  }
  return null
}

boo(){
  console.log('boo')

}

}

like image 374
Yehuda Menahem Avatar asked Feb 14 '18 10:02

Yehuda Menahem


1 Answers

The context in the foo method when called from within the FormControl is not referencing the FormComponent.

You can do the following to fix this behavior using bind to set the context yourself:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {

  formInsurance:FormGroup;
  private id:FormControl;


  constructor(){}


  ngOnInit() {

    const id = new FormControl('',[
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10),
      Validators.pattern('^[0-9]+(-[0-9]+)+$|^[0-9]+$'),
      this.foo.bind(this)
    ]);

    this.id = id;

    this.formInsurance = new FormGroup({
      id
    })
  }


  foo(control:FormControl) {
    this.boo();
    if(control.value){
        return {
          objToReturn: {
              returned: name
          }
        };
      }
    return null
  }

  boo(){
    console.log('boo')

  }
}
like image 87
Gorka Hernandez Avatar answered Nov 15 '22 16:11

Gorka Hernandez