angular 13 form validation dynamic input textbox validation
I'm adding input text boxes dynamically. But form validations are showing by default when I click add source button. How can I show error messages on touch instead of by default.
<form #nonTaxForm="ngForm">
<div *ngFor="let income of incomes; let i=index">
<mat-form-field>
<input matInput [id]="getName('amount')" [name]="getName('amount')"
type="currency" [(ngModel)]="income.cashflowAmount" #amountCtrl="ngModel" required>
<mat-error *ngIf="(amountCtrl.invalid && amountCtrl.touched)">
Must be between $1
</mat-error>
</mat-form-field>
</div>
<button (click)=" addSource()">Add source</button>
</form>
public addSource() {
this.incomes.push({
id: Math.random(),
financialSubtypeCode: null,
cashflowAmount: null
})
}
You need to use reactive form to handle this scenario. In reactive form you need to use FormArray. The sample is here https://www.telerik.com/blogs/angular-basics-creating-dynamic-forms-using-formarray-angular