angular - 反应形式正在验证列表中的所有迭代
问题描述
我在 *ngFor 中使用响应式表单在我的应用程序中进行验证。但是,当我尝试仅验证一次迭代时,表单将在所有迭代中进行验证。
我尝试使用模板驱动的表单,它运行良好。下面是模板驱动表单的工作代码
<div class="form-group col">
<label>Flower License</label>
<input type="text" name="fLicense" class="form-control" [(ngModel)]="f.fLicense" #fLicense="ngModel" [ngClass]="{ 'is-invalid': statusForm.submitted && fLicense.invalid }" required>
<div *ngIf="statusForm.submitted && fLicense.invalid" class="invalid-feedback">
<div *ngIf="fLicense.errors.required">flower License is required</div>
</div>
</div>
对于反应式方法,以下是我的代码 HTML
<div *ngFor="let f of flowers">
<div>{{f.type}} </div>
<form [formGroup]="statusForm" (ngSubmit)="submitStatus()">
<div class="form-group col-sm-4">
<label>Flower License</label>
<input class="form-control" type="text" formControlName="fLicense" [class.invalid]="!statusForm.controls['fLicense'].valid && statusForm.controls['fLicense'].touched ">
<div *ngIf="!statusForm.controls['fLicense'].valid && (statusForm.controls['fLicense'].touched || isSubmitted)">
<div class="invalid-feedback" style="display: block;">Please enter flower License Number</div>
</div>
</form>
</div>
</div>
ts
ngOnInit() {
this.statusForm = this.formBuilder.group({
fLicense: ['', Validators.required],
});
}
submitStatus(f) {
this.isSubmitted = true;
// stop here if form is invalid
if (this.statusForm.invalid) {
return;
}
}
我尝试使用 来执行此操作FormArray
,但我无法包含formControl
在表单数组中。它抛出错误
const newArray = new FormArray({
this.statusForm = new FormGroup({
hempLicense: new FormControl(['', Validators.required])
})
});
解决方案
由于您有值数组,因此您必须创建 FormArray 而不是 FormControl。
this.statusForm = this.formBuilder.group({
fLicense: this.formBuilder.array(this.createFLicenseArray(this.flowers))
});
createFLicenseArray(flowers) {
return flowers.map(flower =>
this.formBuilder.control("", [Validators.required]));
}
然后循环 formArray 控件以显示单个 fLicense
<form [formGroup]="statusForm">
<div class="form-group col-sm-4" formArrayName="fLicense" *ngFor="let flow of fLicenseArray.controls;let i = index">
<label>Flower License</label>
<input class="form-control" type="text" [formControlName]="i">
<div *ngIf="!fLicenseArray.at(i).valid && (fLicenseArray.at(i).touched)">
<div class="invalid-feedback" style="display: block;">Please enter flower License Number</div>
</div>
</div>
</form>
推荐阅读
- java - Hibernate Query parent 基于不同的子类型属性
- javascript - 滚动具有相同类名的元素的jQuery动画
- sql - 在 SQL 中编写或替换双 for 循环(表遍历另一个表遍历)的有效方法
- postgresql - 将 TableQuery 对象作为参数传递会在 Slick/Scala 中导致奇怪的类型错误,但在注入时不会
- python - 如何使用 Python VLC 创建多个播放器并在它们上具有不同的卷?
- android - Stripe future payment getting error 版本 16.1.1 没有这样的 SetUpIntent
- python - 我们可以使用 Discord.py 重写来获取 Discord 用户的延迟(ping)吗?
- azure-devops - 如何分配 Azure DevOps 项目管理员
- scala - Scala 中的编程示例混淆(清单 3.5,创建可变和不可变集)
- c# - 根据使用 System.IO.Ionic.Zlib.DotNetZip.dll 压缩的 db 列大小获取未压缩文件的大小