向 Angular 材料禁用字段添加验证 [英] Add validation to Angular material disabled field

查看:21
本文介绍了向 Angular 材料禁用字段添加验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简化的情况是,在我的表单上,我有两个字段 - A 和 B.

The simplified scenario is whereby on my form I have two fields - A and B.

字段 A 是必需的并已启用.字段 B 也是必需的,但由于在字段 A 中键入的数据而被禁用和仅填充(动态),在某些情况下,B 可能会被解析为 NULL.

Field A is required and enabled. Field B is also required but disabled and only populated (dynamically) as a result of data keyed in field A, ad as it happens in certain cases B may be resolved as NULL.

除非两个字段都被填充,否则用户应该无法提交表单,因此我需要向字段 B(禁用/动态填充)添加必需的验证.

The user should not be able to submit the form unless both fields are populated, therefore I need to add required validation to field B (disabled/dynamically populated).

虽然所需的验证对于启用的字段工作正常,但对于禁用的字段似乎被忽略了.

While the required validation works fine for enabled fields it seems ignored for the fields that are disabled.

<mat-form-field>
  <input name="FieldA" matInput formControlName="FieldA" placeholder="Field A" [maxLength]="6">
  <mat-error *ngIf="formErrors.FieldA">{{ formErrors.FieldA }}</mat-error>
</mat-form-field>

<mat-form-field>
  <input name="FieldB" matInput formControlName="FieldB" placeholder="Field B">
  <mat-error *ngIf="formErrors.FieldB">{{ formErrors.FieldB }}</mat-error>
</mat-form-field>


buildForm() {
  this.form = this.form.group({
      FieldA: ['', [Validators.required]],
      FieldB: [{ value: '', disabled: true }, [Validators.required]],
  });

有什么方法可以在不启用 HTML 的情况下向 FieldB 添加验证吗?

Is there any way I can add validation to FieldB in HTML without enabling it?

推荐答案

使用 readonly 代替 disabled.这两个属性之间的区别在于 disabled 字段在表单提交时被忽略,而 readonly 字段在提交时被包含.不幸的是,Angular 在使用 Reactive Forms Approach 时不支持 readonly 选项,但您可以使用属性绑定轻松实现:

Instead of disabled use readonly. The difference between these two attributes are that disabled fields are ignored on form submit and readonly fields are included on submit. Unfortunatelly angular does not support readonly option while using Reactive Forms Approach, but you can easily do it using property binding:

另一个选项是在提交函数时(在提交调用之前)以编程方式启用此字段.

Another option is to enable this field programmatically on submitting function (before the submit call).

您还可以通过调用 this.form.getRawValue(); 来获取标记为禁用控件的值;

You can also get values which are marked as a disabled controls by calling this.form.getRawValue();

来自源代码注释:

/**
* FormGroup 的聚合值,包括任何禁用控件.
*
* 如果您想包含所有值无论禁用状态如何,都使用此方法.
* 否则,value 属性是获取组值的最佳方式.
*/

/**
* The aggregate value of the FormGroup, including any disabled controls.
*
* If you'd like to include all values regardless of disabled status, use this method.
* Otherwise, the value property is the best way to get the value of the group.
*/

getRawValue(): 任何;

getRawValue(): any;

这篇关于向 Angular 材料禁用字段添加验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆