Issue with passing objects from FormBuilder

179 views Asked by At

As I'm trying to pass objects from formBuilder to another AbstractControl function of typescript file.

But not able to accomplish while passing data.


Stackblitz Here is the coding snippets

Main.component.ts

import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';
import { PasswordStrengthValidator } from './PasswordStrengthValidator';

let obj = {};
obj.passwordLength  = 12;
obj.lowercaseNo     = 3;
...

this.passwordForm = this.formBuilder.group({
    password: new FormControl('', Validators.compose([
      Validators.required,
      Validators.minLength(obj.passwordLength),
      Validators.maxLength(30),
      PasswordStrengthValidator
    ])),
  }, {
    validators: this.password.bind(this)
  });
}

PasswordStrengthValidator.ts

import { AbstractControl, ValidationErrors } from '@angular/forms';

export const PasswordStrengthValidator = function (control: AbstractControl): ValidationErrors | null {
    console.log(obj); // object values needs to be displayed here
    ...
}

Is it possible to achieve replacing the above code to the main component itself or are there any better way to get around this issue

1

There are 1 answers

1
Guilhermevrs On BEST ANSWER

You could use a factory:

<

export const PasswordStrengthValidatorFactory = (passObject: any) => {
  return function(control: AbstractControl): ValidationErrors | null {
    // In console required to display those values in the passObject
    console.log(passObject);

    return null;
  };
};
constructor(fb: FormBuilder) {
    console.log(this.passObject);
    this.myForms = fb.group({
      password: [null, Validators.compose([
        Validators.required, Validators.minLength(8), PasswordStrengthValidatorFactory(this.passObject)])]
    });

Link to stackblitz