Angular 2获取动态FormGroup名称

时间:2017-12-08 09:43:46

标签: angular formgroups

https://angular.io/api/forms/FormGroupName这里如何获取FormGroupName。

如果FormGroupName是动态的,如何获取/修补/更新值?

    <div class="row" *ngFor="let itemrow of searchForm.controls.addresses.controls; let ind=index" [formGroupName]="ind">
   <input class="form-control" formControlName="name">
   <input class="form-control" formControlName="time">
</div>

searchForm.value对象:

"addresses": [
    {
      "address": "",
      "name": 0,
      "time": 0,
 },
    {
      "address": "",
      "name": 0,
      "time": 0,
    }
  ]

如何更新currentGFormGroupName中的输入值?

1 个答案:

答案 0 :(得分:1)

您可以在代码中创建新的表单组

<强>组件

export class AppComponent {
  addresses = [
    {
      address: 'aa',
      name: 'aa',
      time: 'aa'
    },
    {
      address: 'bb',
      name: 'bb',
      time: 'bb'
    }
  ];

  formGroup: FormGroup;
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = new FormGroup({});
    let addressGroup = new FormGroup({});

    this.addresses.map((group, index) => {
      const name = 'group-' + index.toString();
      const formGroup = this.fb.group({
        address: [group.address],
        name: [group.name],
        time: [group.time]
      });
      addressGroup.addControl(name, formGroup);
    })

    this.formGroup.addControl('addresses', addressGroup);
  }

}

<强>模板

<form [formGroup]="formGroup">
  <div formGroupName="addresses">
    <div *ngFor="let address of addresses; let i = index">
      <div formGroupName="{{'group-'+i}}">
        <input type="text" formControlName="address"/>
        <input type="text" formControlName="name"/>
        <input type="text" formControlName="time"/>
      </div>
    </div>
  </div>
</form>