动态表 tr 角度 5 的表单验证



我有动态table tr,每行包含一个提交按钮。我还动态应用了input控件名称。基于tr行验证启用/禁用按钮的最佳方法是什么?

<form #form1="ngForm">
<table>
<thead><tr><th>Name</th><th>Email</th><th>Action</th></tr></thead>
<tbody>
<tr *ngFor="let value of data; let i=index">
<td><input type="text" name="name{{i}}" #nameInput="ngModel" [(ngModel)]="dataModel.name" [value]="value.name" required /></td>
<td><input type="text" name="email{{i}}" #emailInput="ngModel" [(ngModel)]="dataModel.email" [value]="value.email" required /></td>
<td><button type="submit" [disabled]="form1.form.invalid">Submit</button></td>
</tr>
</tbody>
</table>
</form>

在这里,上面的[disabled]条件适用于所有行,但我想根据每一行应用它。

与其使用ngModel,我建议您使用FormGroup

TS

public form1: FormGroup;
ngOnInit(){
this.form1 = this.fb.group({});
}

获得数据后,您可以进行表单验证。

for(index i = 0 ; i < resDeta.length ; index++){
if (resDeta.req === 'TRUE') {
const control: FormControl = new FormControl(null, Validators.required);
this.form1.addControl(resDeta[index].name, control);
}else{
const control: FormControl = new FormControl(null);
this.form1.addControl(props.name, control);
}
}

.HTML

<form [formGroup]="form1" (ngSubmit)="Submit(form1)">
<table>
<thead><tr><th>Name</th><th>Email</th><th>Action</th></tr></thead>
<tbody>
<tr *ngFor="let prop of resDeta; let i=index">
<td><input type="text" [formControlName]="prop.name" [id]="prop.name" [name]="prop.name" placeholder="Enter {{prop.label}}" class="form-control" [attr.maxlength]="prop.length" [value]="prop.name"></td>
<td><input type="text" [formControlName]="prop.name" [id]="prop.name" [name]="prop.name" placeholder="Enter {{prop.label}}" class="form-control" [attr.maxlength]="prop.length" [value]="prop.email"></td>
<td><button type="submit" [disabled]="!form1.valid">Submit</button></td>
</tr>
</tbody>
</table>
</form>

我使用响应式表单数组来做到这一点,也许它正在帮助您。 附上下面的链接 在此处输入链接说明

<button (click)="addbutton()">Add</button>
<ul [formGroup]="formName" class="listTable">
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>description</th>
<th>Action</th>
</tr>
</thead>
</table>
<ul formArrayName="items" class="listTable">
<li *ngFor="let value of formName.get('items').controls; let ix = index">
<form [formGroupName]="ix">
<table class="table table-striped">
<tbody>
<tr>
<td>
<input type="text" formControlName="name"  required/>
</td>
<td>
<input type="text" formControlName="description"  required/>
</td>
<td>
<button type="submit" class="btn btn-primary" [disabled]="value.invalid">Submit</button>
</td>
</tr>
</tbody>
</table>
</form>
</li>
</ul>
</ul>

最新更新