In my code, there is a part where I need to make certain fields required. Initially, only the emailAddress field is required, but under a specific condition (res.isSuccess === true), I also need to set firstName, lastName, and companyName as required.
The issue I'm facing is that the mat error message is already displayed upon the initial load, which should not happen. It should only appear when a field like the firstName is touched or clicked.
Any thoughts on how to resolve this problem? Thank you.
#html
<mat-form-field class="full-width" appearance="fill" style="margin-top: 26px;">
<mat-label>First Name *</mat-label>
<input matInput formControlName="firstName">
<mat-error
*ngIf="modelForm.get('firstName').hasError('required') && (modelForm.get('firstName').touched || modelForm.get('firstName').dirty)">
First Name is required.
</mat-error>
</mat-form-field>
getStarted() {
this.AccountRoleDetails = null;
if (this.userService) {
this.userService
.getUserEmail(this.accountId, this.modelForm.value['emailAddress'])
.subscribe(
(res: any) => {
if (res.isSuccess === true) {
this.setRequiredValidations();
}
});
.........
#Code
initFormGroup() {
this.modelForm = this.formBuilder.group({
id: [this.model.id || 0],
emailAddress: [this.model.emailAddress, Validators.required],
firstName: this.model.firstName,
roleId: this.model.roleId,
lastName: this.model.lastName,
phoneNumber: this.model.phoneNumber,
companyName: this.model.companyName,
});
}
#code 2
setRequiredValidations() {
this.modelForm.get('firstName').setValidators(Validators.required);
this.modelForm.get('lastName').setValidators(Validators.required);
this.modelForm.get('companyName').setValidators(Validators.required);
this.modelForm.updateValueAndValidity();
}