[英]How to assign formGroup to an array for form validation
I have a repeater section in angular, i followed the below method to achive it, but i want to validate the form (Enable or disable the final submit button based on the validation),Here is the sample code.我在 angular 中有一个转发器部分,我按照下面的方法来实现它,但我想验证表单(根据验证启用或禁用最终提交按钮),这是示例代码。
ts file:- ts 文件:-
private formBuilder : FormBuilder
) { }
formInfoHolder = [];
onAdd(){
let newForm = {
let newForm = {
subText : new FormControl('',[Validators.required,Validators.maxLength(250)]),
header : new FormControl('',[Validators.required,Validators.maxLength(20)]),
link : new FormControl('',[Validators.required,Validators.pattern('[a-zA-Z]*')]),
}
}
this.formInfoHolder.push(this.formBuilder.group(newForm))
}
delete(toDelete){
let del : any[] = [];
for(let form of this.formInfoHolder){
if(toDelete !== form){
del.push(form);
}
}
this.formInfoHolder = del;
}
then in HTML Component然后在 HTML 组件中
<div *ngFor="let form of formInfoHolder">
<form [formGroup]="form">
<label for="username"> Username </label>
<input id="username" type="text" formControlName="username">
<!-- insert other input elements with the formControlName -->
<label for="delete"> Delete </label>
<input id="delete" type="button" (click)="delete(form)">
</form>
</div>
<button (click)="onAdd()">Add</button>
<button [disabled]="//Here i want to validate" (click)="saveInfo()">Save</button>
How do i validate the form(enable the button only if all the fields are filled) which is stored in an array.我如何验证存储在数组中的表单(仅在填写所有字段时才启用按钮)。
Here is a Stackblitz example for what you are looking for I have used formarray and added formgroups into it, adding and removing formgroups becomes easy in formarray.这是您正在寻找的Stackblitz 示例我使用了 formarray 并在其中添加了 formgroups,在 formarray 中添加和删除 formgroups 变得很容易。 Also validation also becomes easy because I only have check if the main form in valid
验证也变得容易,因为我只检查主表单是否有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.