Angular2反应形式表格 [英] Angular2 Reactive Form Table

查看:63
本文介绍了Angular2反应形式表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在查找和尝试执行我想做的事情时遇到了麻烦.

I am having some trouble looking up and attempting to do what I want to.

我有一个表格,每一行都有输入,我希望将使用ngFor创建的每一行都视为一个表单组.

I have a table with inputs in each row, and I want each row which is created using an ngFor, to be considered a form group.

在每个表单组中,我想验证一下,如果在该行中填充了任何控件,则需要先填充整个表单组,然后才能完成提交.

Within each form group I want a validation in that if any of the controls are filled within the row, that the entire form group needs to be filled before submission can be done.

这是我到目前为止模板中的内容.

Here is what I have so far in my template.

由于Angular.io,我的组件中还没有任何东西,经过几个小时的搜索,我没有看到任何与我想要的东西接近的东西.

I don't have anything in the component yet as Angular.io and searching around for a few hours has not shown me anything close to what I want.

<form>
        <table id="table" class="mdl-data-table mdl-js-data-table mdl-data-table mdl-shadow--2dp">
            <thead>
                <tr>
                    <th>Day</th>
                    <th>Description</th>
                    <th>Open Time</th>
                    <th>Close Time</th>
                </tr>
            </thead>

            <tbody>

                <tr *ngFor="let scheduleDetail of scheduleDetails">
                    <td style="padding: 0 8px 0 8px;">{{weekdayConverter(scheduleDetail.dayId)}}</td>
                    <td class="pad-input">
                        <mdl-textfield style="max-width:100px;" type="text" class="font" name="description" [(ngModel)]="scheduleDetail.description"></mdl-textfield>
                    </td>
                    <td>
                        <mdl-textfield style="max-width:75px" type="text" error-msg="hh:mm" name="openTime" pattern="([01]\d|2[0-3]):?([0-5]\d)" [(ngModel)]="scheduleDetail.openTime"></mdl-textfield>
                    </td>
                    <td>
                        <mdl-textfield style="max-width:75px" type="text" error-msg="hh:mm" name="closeTime" pattern="([01]\d|2[0-3]):?([0-5]\d)" [(ngModel)]="scheduleDetail.closeTime"></mdl-textfield>
                    </td>
                </tr>

            </tbody>

        </table>
    </form>

更新

在模板中添加了以下内容:

Update

Added the following to the template:

将输入更改为:

<mdl-textfield (keyup)="formChange(scheduleDetail)" style="max-width:100px;" type="text" class="font" name="description" [(ngModel)]="scheduleDetail.description"></mdl-textfield>

在组件中添加了以下内容:

Added the following to the component:

    formChange(detail:scheduleDetail){
if(this.checkValid(detail)==false)
this.scheduleDetails.filter(detail => detail == detail)[0].require=true;
else
this.scheduleDetails.filter(detail => detail == detail)[0].require=false;

this.checkForm();
}

checkValid(detail:scheduleDetail){
if(detail.description!=null && detail.description!=""){
  if(this.checkTime(detail))
    return true
  else 
    return false
}
else
  return true
}

checkTime(detail:scheduleDetail){
  if(
    (detail.openTime!=null && detail.closeTime!=null) && 
    ( detail.openTime!="" && detail.closeTime!="") &&
    (this.checkRegExp(detail.openTime) && this.checkRegExp(detail.closeTime))
    ){
    return true
    }

  else if((this.checkRegExp(detail.openTime) && this.checkRegExp(detail.closeTime))){
    return true
  }
  else return false
}

checkRegExp(time:string){
let timeRegExp = /([01]\d|2[0-3]):?([0-5]\d)/;

if(timeRegExp.test(time)){
  return true;
}
else
  return false;

}

checkForm(){
let valid: boolean = true;
  this.scheduleDetails.forEach(detail => {
    if(detail.require==true){
      valid = false;
    }
  });

    this.scheduleDetails.forEach(detail => {
    if(detail.description=="" || detail.description==null){
      valid = false;
    }
  });
this.formValid = valid;
}

推荐答案

模型驱动的表单

您使用的是模板驱动的表单,该表单难以缩放和维护.

Model Driven Forms

You are using a template driven form, which is hard to scale, and maintain.

在这里,我将指导您迁移到模型驱动的表单.

Here, i will guide you to migrate to a model driven form.

export class WeekScheduleComponent {

// Our empty Form
myForm: FormGroup;

constructor(private fb: FormBuilder){
 // We inject FormBuilder to our component

 // Now, we instantiate myForm with FormBuilder
 // Notice that myForm is a FormGroup which contains an empty FormArray
    this.myForm = this.fb.group({
                   scheduleDetail: this.fb.array([])
                  })
}

addRow(){
    // This function instantiates a FormGroup for each day
    // and pushes it to our FormArray

    // We get our FormArray
    const control = <FormArray>this.myForm.controls['scheduleDetail'];

    // instantiate a new day FormGroup;
    newDayGroup: FormGroup = this.initItems();

    // Add it to our formArray
    control.push(newDayGroup);
}

initItems(): FormGroup{
    // Here, we make the form for each day

    return this.fb.group({
               description: [null, Validators.required],
               openTime: [null, Validators.required],
               closeTime: [null, Validators.required]
           });
}

submit(){
    // do stuff and submit result
    console.log(this.myForm.value);
}
}

在您的模板中:

<form [formGroup]="myForm" *ngIf="myForm">
     <table formArrayName="scheduleDetail">

            <tr *ngFor="let item of myForm.controls.scheduleDetail.controls; let i=index"
                [formGroupName]="i" >

                <td><input type='text' formControlName="description"></td>
                <td><input type='text' formControlName="openTime"></td>
                <td><input type='text' formControlName="closeTime"></td>

            </tr>

     </table>
</form>

<button (click)="addRow()">Add new item</button>
<button (click)="submit()" [disabled]="!myForm.valid">Submit</button>

这篇关于Angular2反应形式表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆