Search code examples
angularangular2-formsangular2-services

Angular 2 `Cannot read property 'dataService' of undefined`


I am using Angular 2 and I am trying to call this inside a method, but I am getting an error: Cannot read property 'dataService' of undefined

passwordMatchValidator(g: FormGroup) {
                        console.log(this.dataService);
                        return g.get('password').value === g.get('repeat').value ? null : {'mismatch': true};
        }

When I can this.dataService outside the method it works, is this because this is now FormGroup? and if so, how would I call this.dataService inside this method?

    import { DataService } from '../../services/data.service';

    @Component({
            selector: 'app-register',
            templateUrl: './register.component.html',
            styles: []
    })
    export class RegisterComponent{

    constructor(private fb: FormBuilder,
                    private locationService: LocationService,
                    private dataService: DataService){}

buildForm(): void {    

this.step1Form = this.fb.group({
                username: new FormControl('', {
                        validators: [Validators.required,
                        Validators.minLength(4)],
                }),
                email: new FormControl('', {
                        validators: [Validators.required,
                        Validators.pattern("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")],
                }),
                password: new FormControl('', {
                        validators: [Validators.required,
                        Validators.minLength(8)],
                }),
                repeat: new FormControl('', {
                        validators: [Validators.required,
                        Validators.minLength(8)],
                }),
                }, { validator: this.passwordMatchValidator });

}

    passwordMatchValidator(g: FormGroup) {
                            console.log(this.dataService);
                            return g.get('password').value === g.get('repeat').value ? null : {'mismatch': true};
            }

    }

Solution

  • When you assign validator to control, you have to save context, for example:

    fb.group({
      password: [null, this.passwordMatchValidator.bind(this)]
    })