[英]Using Variables in Angular Form Validators
I'm trying to use a variable or enum in my form validators for my Angular application.我正在尝试在我的 Angular 应用程序的表单验证器中使用变量或枚举。 For example instead of
例如,而不是
TestValue: ['', [Validators.min(0), Validators.max(72)]];
having the numbers hardcoded in, I would like to pass in either an enum or a variable in the Validators argument that would have those number values so I can use them across components.将数字硬编码后,我想在 Validators 参数中传入一个枚举或一个变量,该参数将具有这些数字值,以便我可以跨组件使用它们。
Is this possible?这可能吗?
kjamp.坎普。 Yes you can set variables value to validate form.
是的,您可以设置变量值来验证表单。 Please have to to the following code:
请务必使用以下代码:
In Component file:在组件文件中:
form: FormGroup;
min;
max;
constructor(private fb: FormBuilder) {
this.min = 0;
this.max = 72;
this.createForm(this.min, this.max);
}
createForm(min, max) {
this.form = this.fb.group({
capacity: ['', [Validators.min(min), Validators.max(max)]],
});
}
submit() {
console.log(this.form.value);
console.log(this.form.controls['capacity'].errors);
}
In your your HTML file在您的 HTML 文件中
<form [formGroup]="form" (ngSubmit)="submit()">
<input type="number" formControlName="capacity" name="capacity" />
<button>Submit</button>
</form>
I hope this will help you to find your expected solution.我希望这将帮助您找到预期的解决方案。 Thank you.
谢谢你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.