从 FormBuilder 传递对象的问题
Issue with passing objects from 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)])]
});
因为我试图将对象从 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)])]
});