要在Angular 7中动态/更新参数进行自定义验证,可以使用自定义验证器函数以及FormGroup的setValidators方法。以下是一个示例解决方案:
function minLengthValidator(minLength: number) {
return (control: AbstractControl): { [key: string]: any } | null => {
const value = control.value;
if (value && value.length < minLength) {
return { 'minLength': { minLength } };
}
return null;
};
}
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
password: ['', Validators.compose([Validators.required, minLengthValidator(8)])]
});
}
// 动态更新验证参数
updateMinLength(minLength: number) {
const passwordControl = this.myForm.get('password');
passwordControl.setValidators(Validators.compose([Validators.required, minLengthValidator(minLength)]));
passwordControl.updateValueAndValidity();
}
}
在上述示例中,密码字段的最小长度由updateMinLength方法动态更新。每当点击"Update Min Length"按钮时,将调用该方法,并传入新的最小长度作为参数。该方法将使用setValidators方法更新密码字段的验证器,并调用updateValueAndValidity方法来重新验证字段。
这就是一个使用自定义验证器函数和setValidators方法在Angular 7中动态/更新参数进行自定义验证的解决方案。