The simplified scenario is whereby on my form I have two fields - A and B.
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.
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]],
});
Is there any way I can add validation to FieldB in HTML without enabling it?
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:
<input type="text" formContolName="FieldB" [readonly]="isReadonly">
Another option is to enable this field programmatically on submitting function (before the submit call).
EDIT: You can also get values which are marked as a disabled controls by calling this.form.getRawValue();
From the source code comment:
/**
* The aggregate value of theFormGroup
, including any disabled controls.
*
* If you'd like to include all values regardless of disabled status, use this method.
* Otherwise, thevalue
property is the best way to get the value of the group.
*/getRawValue(): any;