angular 13表单验证动态输入文本框验证
我正在动态地添加输入文本框。但默认情况下,当我单击添加源按钮时,会显示表单验证。如何在触摸时显示错误信息而不是默认值
<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
})
}
您需要使用响应式表单来处理此场景。在响应式表单中,你需要使用FormArray。示例在这里https://www.telerik.com/blogs/angular-basics-creating-dynamic-forms-using-formarray-angular