I created a dynamic form, in which you can add or remove fields with dedicated buttons:
The problem is that when we add a new field, the form validations are immediately triggered causing the error messages to be displayed:
I would like to trigger it only if the user try to submit the form when there are errors. And of course the form cannot be submitted if there are errors (Validators.required, nicknameValidator())
Here is the code that generate a new row in the form:
createNicknameFormGroup(): any {
return new FormGroup({
nickname: new FormControl('', Validators.required, this.isValidNicknameService.nicknameValidator())
}, { updateOn: 'blur' })
}
And the html code responsible of displaying those rows:
<div *ngFor="let nickname of nicknamesFormArray.controls; let i = index;" class="row">
<div [formGroupName]="i">
<mat-form-field appearance="outline" class="nickname-form-field">
<mat-label>{{formFieldsInfo.nicknames.label}}</mat-label>
<input matInput [placeholder]=formFieldsInfo.nicknames.placeholder formControlName="nickname"
type="text"
class="form-control">
<mat-hint>{{formFieldsInfo.nicknames.hint}}</mat-hint>
<mat-error *ngIf="nicknamesFormArray.controls[i].get('nickname').errors?.required">
{{formFieldsInfo.nicknames.errorMessages.required}}
</mat-error>
<mat-error *ngIf="nicknamesFormArray.controls[i].get('nickname').errors?.shouldNotStartWithA">
{{formFieldsInfo.nicknames.errorMessages.shouldNotStartWithA}}
</mat-error>
</mat-form-field>
<mat-icon (click)="removeNicknameFromNicknamesFormArray(i)" class="clear">
clear
</mat-icon>
</div>
</div>
setValidators()
and setErrors()
if you want.setValidators()
https://angular.io/api/forms/AbstractControl#setValidators https://angular.io/api/forms/AbstractControl#setErrors
I recommend read more API options.