forms - Angular2 响应式(Reactive)表格

标签 forms angular html-table controls

我在抬头和尝试做我想做的事情时遇到了一些困难。

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

在每个表单组中,我想要一个验证,如果行中有任何控件被填充,则需要在提交完成之前填充整个表单组。

这是我目前在模板中的内容。

我在组件中还没有任何东西,因为 Angular.io 搜索了几个小时并没有向我展示任何接近我想要的东西。

<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>

更新

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

将输入更改为:

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

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

    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;
}

最佳答案

模型驱动表单

您正在使用难以扩展和维护的模板驱动表单。

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

组件

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>

关于forms - Angular2 响应式(Reactive)表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155112/

相关文章:

html - 为什么这个 HTML 表格在 Chrome 中不能正常工作?

javascript - 单击按钮显示/隐藏元素

javascript - 创建一个表单并编辑该表单但不保存(以 Angular 形式)?

validation - 将输入类型编号限制为 Angular 2 中的小数点后 2 位

html - 可滚动的 tbody 不占用所有可用宽度

css - Angular 4+ : How to use icons from svg file

javascript - typescript 上有一个 `Object.values()` 吗?

javascript - 使用 jquery 动态确定的表单变量

angularjs - 如何在最小长度验证angularjs中显示输入长度

javascript - 是否可以在没有表单的情况下通过 JS 发布文件?