Angular4 Reactive嵌套表单问题

时间:2017-08-13 08:23:11

标签: angular angular2-template angular2-forms angular-reactive-forms angular4-forms

我正在使用Angular 4反应来创建嵌套表单。我的表单结构如下

  • 表单组(userform)

  • FormArray(用户)

  • FormGroup(IDX)

完整的位于表单组下,每个表格行位于 FormArray(用户)表数据单元格位于Formgroup(idx)下。

错误:

appComponent.html:20 ERROR Error: Cannot find control with path: 'users -> 0 -> '

HTML:

<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
    <tbody formArrayName="users">
        <tr *ngFor="let user of users.controls; index as idx">
            <div [formGroupName]="idx">
          <td>
            <div class="mdl-select mdl-js-select mdl-select--floating-label">
            <select class="mdl-select__input" id="projectname{{i}}" name="projectname{{i}}"  [formControlName]="projectname">
              <option *ngFor="let project of projects;let first=first;let last:last">{{project.projectname}}</option>
            </select>
            <label class="mdl-select__label" for="professsion">Select Project Name</label>
            </div>
          </td>
          <td>
            <div class="mdl-textfield mdl-js-textfield">
              <input class="mdl-textfield__input" type="text" pattern="[0-9]*" id="sunday{{i}}" name="sunday{{i}}"  [formControlName]="sunday">
              <span class="mdl-textfield__error">Digits only</span>
            </div>
          </td>
    </tr>
    </table>
</form>

TS:

export class appComponent implements OnInit {

  ngOnInit() {

  }

  userForm = new FormGroup({

      users: new FormArray([
               new FormControl()
            ])
      });

      get userName(): any {
        return this.userForm.get('name');
      }
      onFormSubmit(): void {
        this.logData();
      }
      get users(): FormArray { 
        return this.userForm.get('users') as FormArray; 
      }
      addUserField() { 
        this.users.push(new FormControl()); 
      }
      deleteUserField(index: number) {
        this.users.removeAt(index);
      }

      logData(){
        for(let i = 0; i < this.users.length; i++) {
          console.log(this.users.at(i).value);
        }
      }

    }

1 个答案:

答案 0 :(得分:1)

首先,您的表单控件与您的模板不匹配。现在,在users数组中,您只有一个未指定的表单控件。相反,您应该具有要在模板中显示的两个表单控件。假设您想在数组中使用初始的空表单组,请执行以下操作:

this.userForm = this.fb.group({
  users: this.fb.array([
    this.initUsers();
  ])
});

initUsers() {
  return this.fb.group({
    projectname: [''],
    sunday: ['']
  });
}

其中fb引用构造函数中注入的FormBuilder

通过上面的内容,您现在可以在表单数组中使用两个表单控件。如果要在表格中添加新表单组(行),也可以调用initUsers()

然后您需要删除模板中formcontrolName周围的括号,而不是

[formControlName]="projectname"
....
[formControlName]="sunday"

做的:

formControlName="projectname"
...
formControlName="sunday"

DEMO:http://plnkr.co/edit/qraDXUYOaOL9eClTqjqh?p=preview

另外值得一提的是,我看到您在模板中对pattern进行了sunday验证,将其删除并设置Validators.pattern()代替您的表单控件。