Serhio g. Lazin
Serhio g. Lazin

Reputation: 9642

Angular 2 Get Dynamic FormGroup name

https://angular.io/api/forms/FormGroupName here how get FormGroupName.

How to get/patch/update values if FormGroupName is dynamic?

    <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 object:

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

How to update inputs value inside currentGFormGroupName ?

Upvotes: 4

Views: 9713

Answers (1)

Kyrsberg
Kyrsberg

Reputation: 440

You could create new form group in code

Component

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);
  }

}

Template

<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>

Upvotes: 2

Related Questions