从FormBuilder传递对象的问题

问题描述

当我试图将对象从formBuilder传递到打字稿文件的另一个AbstractControl函数时。

但是在传递数据时无法完成。


Stackblitz这是代码

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
    ...
}

是否可以将上面的代码替换为主组件本身,或者有什么更好的方法解决此问题

解决方法

您可以使用工厂:

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