0

I have skills as FormArray. inside each skill I have rate ControlFormName.

And I have update button. when I click it should patch the values into skills control.

But why nothing happens? it should have input which bind to rate property.

Stackblitz example

import { Component, VERSION } from "@angular/core";
import { FormGroup, FormArray, Validators, FormBuilder } from "@angular/forms";

@Component({
    selector: "my-app",
    template: `
        form value: {{ form.value | json }}
        <br />
        <form [formGroup]="form" (ngSubmit)="submit()">
          <div formArrayName="skills">
            <div
              *ngFor="let skill of skills.controls; let i = index"
              [formGroupName]="i"
              class="skill"
            >
              <p>
                <b>skill : {{ i + 1 }}</b>
              </p>
              <p>
                skill Rate :
                <input formControlName="rate" />
              </p>
            </div>
          </div>
          <button (click)="update()">update</button>
        </form>
      `
})
export class AppComponent {
    name = "Angular " + VERSION.major;

    form = new FormGroup({
        skills: new FormArray([])
    });

    get skills() {
        return this.form.get("skills") as FormArray;
    }

    update() {
        this.skills.patchValue([{ rate: 100 }, { rate: 50 }]);
    }
    submit() {}
}

2 Answers 2

1

A FormArray is an array of AbstractControls. The patchValue() and setValue() functions allows you to update the value of a form or the part of a form. But this form needs to be defined firstly.

Here your form doesn't know anything about rate.

Either you need to populate your FormArray on creation :

form = new FormGroup({
    skills: new FormArray([
      new FormGroup({
        rate: new FormControl()
      }),
      new FormGroup({
        rate: new FormControl()
      })
    ])
  });

Either you need to populate it on the fly :

update() {
    const values = [100, 50];

    values.forEach(value => {
      this.skills.push(
        new FormGroup({
         rate: new FormControl(value)
        })
      )
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

1

You can try with this code below:

  1. Add FormBuilder in your constructor
 constructor(private fb: FormBuilder) {}
  1. change your updated method with this code below:
update() {
    [{ rate: 100 }, { rate: 50 }].forEach(rate => {
      this.skills.push(this.fb.group(rate))
    })
  }

Now, it's will working fine.

You can check an example here: https://stackblitz.com/edit/angular-ivy-dq6gls?file=src/app/app.component.ts

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.