Form validation for dynamic table tr angular 5

余生长醉 提交于 2019-12-02 11:27:04

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!