启用以正确绑定Angular formArray数据

时间:2019-09-20 12:14:07

标签: angular angular-reactive-forms formarray

我想在formArray内创建FormGroupformArray有多个formGroup,并且创建了FormGroup,但是如果我在输入标签中写了0索引但数据反映在最后{{ 1}}。

HTML:

FormGroup

TS:

<form [formGroup]="form">
  <table>
  <thead>
    <tr>
      <th>City</th>
      <th>Employee id</th>
    </tr>
  </thead>
  <tbody formArrayName="myNewArray">
    <tr *ngFor="let controls of form.get('myNewArray').controls; let i = index">
      <div [formGroupName]="i">
        <td>
         <mat-form-field>
          <input matInput class="size-input" formControlName="first">
        </mat-form-field>
      </td>
      <td>
         <mat-form-field>
          <input matInput class="size-input" formControlName="second">
        </mat-form-field>
      </td>
      </div>
    </tr>
  </tbody>
  <pre>{{form.value | json}}</pre> 
</table>
</form>

也请检查链接:-https://stackblitz.com/edit/angular-ptbvgd?file=src/app/app.component.html

1 个答案:

答案 0 :(得分:1)

我已经稍微改变了ts。希望对您有所帮助:

    @Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
 form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    myNewArray: this.fb.array([])
  });

  }
  ngOnInit(): void {
    const formGroup = { };
    let abc = ['bonus', 'contributionretirement'];
    abc.forEach(formControl => {
      formGroup[formControl] = new FormControl("", Validators.required);
    });
    console.log(formGroup);

    for (let value in abc) {
      let formGroupArray = this.myNewArray;
      formGroupArray.push(this.setUsersFormArray());
    }
    console.log(this.form.controls.myNewArray);
    for (let controls of this.myNewArray.controls) {
      console.log(controls,'tttt');
    }
  }

  get myNewArray(): FormArray{
    return this.form.get('myNewArray') as FormArray;
  }
  private setUsersFormArray ():FormGroup {
    const formGroup = new FormGroup({});
    let abc = ['bonus', 'contributionretirement'];
    abc.forEach(formControl => {
      formGroup.addControl(formControl, new FormControl("", Validators.required));
    });
    return formGroup;
  }

}