【问题标题】:Using Variables in Angular Form Validators在 Angular 表单验证器中使用变量
【发布时间】:2021-05-21 21:28:28
【问题描述】:

我正在尝试在我的 Angular 应用程序的表单验证器中使用变量或枚举。例如,而不是

TestValue: ['', [Validators.min(0), Validators.max(72)]];

将数字硬编码后,我想在 Validators 参数中传入一个枚举或一个变量,该参数将具有这些数字值,以便我可以跨组件使用它们。

这可能吗?

【问题讨论】:

  • 是的。这就是接受参数的原因。
  • 我该如何添加这个?

标签: javascript arrays angular forms validation


【解决方案1】:

kjamp。是的,您可以设置变量值来验证表单。请务必到以下代码:

在组件文件中:

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);
}

在您的 HTML 文件中

<form [formGroup]="form" (ngSubmit)="submit()">
    <input type="number" formControlName="capacity" name="capacity" />
    <button>Submit</button>      
</form>

我希望这将帮助您找到预期的解决方案。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2016-09-19
    • 2016-07-06
    • 1970-01-01
    • 2022-12-22
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多