我创建了一个动态表单,您可以在其中使用专用按钮添加或删除字段:
问题是当我们添加一个新字段时,会立即触发表单验证,从而导致显示错误消息:
我只想在用户在出现错误时尝试提交表单时触发它。当然如果有错误也不能提交表单(Validators.required,nicknameValidator())
以下是在表单中生成新行的代码:
createNicknameFormGroup(): any {
return new FormGroup({
nickname: new FormControl('', Validators.required, this.isValidNicknameService.nicknameValidator())
}, { updateOn: 'blur' })
}
以及负责显示这些行的 html 代码:
<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>