4

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 内的输入值?

4

1 回答 1

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>
于 2017-12-08T12:16:36.050 回答