我已经浏览了stackOverflow和Internet中的所有答案。
我只有FormGroup的FormArray解决方案,但我只想将数据保存在FormArray中
WorkId:["a","b","c"]
我从服务器获得的数据也采用上述格式
这是我的代码
WorkIDList: this.formBuilder.array([
this.formBuilder.control(""), Validators.required
], Validators.required);
get WorkIDlist() {
return this.registerForm.get("WorkIDList") as FormArray;
}
addworkidlist() {
this.WorkIDlist.push(this.formBuilder.control(""));
}
submit(data, event: Event) {
this.submitted = true;
if (this.registerForm.invalid) {
this.validateAllFields(this.registerForm);
return;
// alert("all fields must be filled");
} else {
event.preventDefault();
console.log("data", data);
}
}
// validation on submit
validateAllFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormArray) {
control.markAsTouched();
}
if (control instanceof FormControl) {
control.markAsTouched({
onlySelf: true
});
} else if (control instanceof FormGroup) {
this.validateAllFields(control);
}
});
}
<div class="form-group">
<div class="col-sm-9" formArrayName="WorkIDList">
<div *ngFor="let address of WorkIDlist.controls; let i=index">
<input class="form-control workIdList" type="text" [formControlName]="i" required />
<!-- <div *ngIf="address.invalid && (address[i].dirty || address[i].touched)"
class="alert alert-danger">
<div *ngIf="address[i].errors.required">
WorkspaceName is required.
</div>
</div> -->
<div *ngIf="address[i].invalid">
<div *ngIf="address.hasError('required')">
Error
</div>
</div>
</div>
<button type="button" (click)="addworkidlist()">Add</button>
</div>
</div>
我无法在 html 中进行验证,也无法通过脚本对submit()
进行错误验证
任何人都可以在这个问题上提供帮助。
提前谢谢。
我找到了在HTML和打字稿中进行验证的解决方案
validateAllFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormArray) {
for (const control1 of control.controls) {
if (control1 instanceof FormControl) {
control1.markAsTouched({
onlySelf: true
});
}
if (control1 instanceof FormGroup) {
this.validateAllFields(control1);
}
}
// control.markAsTouched();
}
if (control instanceof FormControl) {
control.markAsTouched({
onlySelf: true
});
} else if (control instanceof FormGroup) {
this.validateAllFields(control);
}
});
}
<div class="form-group">
<div class="col-sm-9" formArrayName="WorkIDList">
<div *ngFor="let address of WorkIDlist.controls; let i=index">
<input class="form-control workIdList" type="text" [formControlName]="i" required />
<div *ngIf="address.invalid && (address.dirty || address.touched)" class="alert alert-danger">
<div *ngIf="address.hasError('required')">
WorkspaceName is required
</div>
</div>
</div>
<button type="button" (click)="addworkidlist()">Add</button>
</div>
</div>