如何在角度2.4中使用FormArray

时间:2017-02-19 18:15:33

标签: angular

我正在使用angular 2.4并且需要使用“FormArray”制作动态表单,但HTML根本不会重新识别我的数组。 我有这样的错误: 引起:无法找到名称为'0'的控件

ts文件:

    import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';

@Component({
  selector: 'my-formstwo',
  templateUrl: "app/fromstesttwo/fromstesttwo.component.html",
})
export class FromstesttwoComponent  {

    myForm: FormGroup;
    constructor(){
        this.myForm = new FormGroup({
            'dataforms': new FormGroup({
                'username': new FormControl('sh', [Validators.required,Validators.minLength(3)]),
                'email': new FormControl('', 
                    [
                        Validators.required, 
                        Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
                    ])
                }),
            'password': new FormControl('', Validators.required),
            'gender': new FormControl('Fmale',Validators.required),
            'hobys': new FormArray([
                new FormControl('SF')
            ])
        });
    }
    get hobyss(): FormArray { return this.myForm.get('hobys') as FormArray; }
    addHobys() {
     this.hobyss.push(new FormControl()); 
    }
    genders:Array<string> = [
        'Male',
        'Fmale'
    ]
    onSubmit(){
        console.log(this.myForm);
    }
}

html文件:

<div class="clearfix"> </div>
<p> </p>
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div formGroupName="dataforms">
 <div class="form-group">
    <label for="exampleInputEmail1">Username</label>
    <input 
      type="username" 
      class="form-control" 
      id="exampleInputEmail1" 
      placeholder="Username"
      formControlName="username">
  </div>

  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input 
      type="email" 
      class="form-control" 
      id="exampleInputEmail1" 
      placeholder="Email"
      formControlName="email">
      <div *ngIf="!myForm.controls.dataforms.controls.email.valid">
        email inValid
      </div>
  </div>
</div>


  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input 
      type="password" 
      class="form-control" 
      id="exampleInputPassword1" 
      placeholder="Password"
      formControlName="password">
  </div>

  <div class="form-group">
    <div class="radiobottom" *ngFor="let g of genders">
      <input type="radio" name="gender" [value]="g" formControlName="gender">
      {{g}}
    </div>
  </div>


  <div FormArrayName="hobys">
    <div class="form-group" *ngFor="let h of myForm.controls.hobys.controls; let i=index">
     <p> </p>
        <input 
          type="text"
          class="form-control" 
          formControlName="{{ i }}">
    </div> 
  </div>

  <button type="button" class="btn btn-primary" (click)="addHobys()">Hoby</button>
  <button type="submit" class="btn btn-default" [disabled]="!myForm.valid">Submit</button>


</form>

我的错误控制台:

EXCEPTION: Error in app/fromstesttwo/fromstesttwo.component.html:53:10 caused by: Cannot find control with name: '0'

2 个答案:

答案 0 :(得分:2)

问题在于它是formArrayName,而不是FormArrayName

<div formArrayName="hobys">
  <div class="form-group" *ngFor="let h of myForm.controls.hobys.controls; let i = index">
    <p></p>
    <input type="text" class="form-control" formControlName="{{i}}">
  </div> 
</div>

<强>加成:

作为提示,您可以在组件中为controls创建参考,如下所示:

export class FromstesttwoComponent {

  myForm: FormGroup;
  usernameCtrl: FormControl;
  emailCtrl: FormControl;
  passwordCtrl: FormControl;
  genderCtrl: FormControl;
  hobbiesCtrl: FormControl;
  dataFormsCtrl: FormGroup;
  hobbiesCtrl: FormArray;

  constructor() {
    this.usernameCtrl = new FormControl('sh', [Validators.required,Validators.minLength(3)]);
    this.emailCtrl = new FormControl('', 
      [
          Validators.required, 
          Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
      ]
    );
    this.passwordCtrl = new FormControl('', Validators.required);
    this.genderCtrl = new FormControl('Fmale',Validators.required);
    this.hobbiesCtrl = new FormArray([new FormControl('SF')]);

    this.dataFormsCtrl = new FormGroup({
      'username': this.usernameCtrl,
      'email': this.emailCtrl
    });

    this.myForm = new FormGroup({
      'dataforms': this.dataFormsCtrl, 
      'password': this.passwordCtrl, 
      'gender': this.genderCtrl, 
      'hobys': this.hobbiesCtrl 
    });
  }
}

<强>为什么吗

执行此操作您无需使用 get 或其他任何内容来访问controls,您只需直接在模板中访问此内容,如下所示:

而不是:

<div *ngIf="!myForm.controls.dataforms.controls.email.valid">
...
<div class="form-group" *ngFor="let h of myForm.controls.hobys.controls; let i=index">

此:

<div *ngIf="emailCtrl.invalid">
...
<div class="form-group" *ngFor="let h of hobbiesCtrl.controls; let i=index">

答案 1 :(得分:0)

您必须在此FormArrayName="hobys"(小写)

中更改此formArrayName="hobys"

以及此formControlName="{{ i }}"

中的[formControlName]="i"