I have dynamic table tr
and each row contains a submit button. I also applied input
control name dynamically. What is the best way to enable/ disable button based on the tr
row validation?
<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>
Here, above [disabled]
condition applies for all rows but i want to apply it based on the each row.
Instead of using ngModel I would suggest you use FormGroup
.
TS
public form1: FormGroup;
ngOnInit(){
this.form1 = this.fb.group({});
}
Once you get the data you can do a form validation.
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>
i did this using form array in reactive form , may be it's helping you. attached link below enter link description here
<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>
来源:https://stackoverflow.com/questions/52268923/form-validation-for-dynamic-table-tr-angular-5