In my set-up, I have created a form group using reactive forms.
this.transactionForm = fb.group ({
'location': [null, Validators.required],
'shopper': [null],
'giftMessage': [null],
'retailPrice' : [0, Validators.required]
});
Shopper and giftMessage are intended to be optional fields without the requirement for Validators.Required to be set on them. The remaining fields in the form are mandatory.
However, upon loading the page, all fields including the optional ones like shopper and giftMessage are initially marked as ng-invalid. This causes an issue when trying to submit the form as even the optional fields need to be filled in.
I'm puzzled as to why these optional fields are initially marked as ng-invalid. How can I ensure that the optional fields remain valid inside the form group?
For instance, this is how I've configured my select field:
<select [ngModel]="null" formControlName="shopper" style="margin-left:35px;" required>
<option value="null" disabled selected>{{'SelectOption' | translate}}</option>
<option *ngFor="let shopper of shoppers">{{shopper | translate}}</option>
</select>
During runtime, I noticed that the following classes are added to the field:
class="ng-touched ng-pristine ng-invalid"
Attempted solutions included adding these lines to the constructor:
this.transactionForm.controls['shopper'].markAsTouched();
this.transactionForm.controls['shopper']..setErrors({incorrect: false});
Despite these efforts, the control continues to show as ng-invalid.