0

I want to get the values on my simple Form inside a formArray but it's giving me errors. I have tried other solutions like this one but it's not working.

Here's my sample code: https://stackblitz.com/edit/angular-get-array-values

    ----- HTML
<div class="form-group" formArrayName="optionGroup">
   <div *ngFor="let data of menuOptions; let i = index">
                    <div [formGroupName]="i" class=" " id="{{i}}">
                      <input
                        formControlName="optionsQty"
                        class="form-input qty qty{{i}}"
                        type="number"
                        id="qty{{i}}"
                        min="1"
                        [(ngModel)]="defaultOptionQtyTotal"
                      />
        
                      <input
                        formControlName="optionsName"
                        class="form-input"
                        type="text"
                        readonly
                        value=" {{data.name}} {{i}}"
                        id="optName{{i}}"
                      />
        
                      $<input
                        formControlName="optionsCost"
                        class="form-input"
                        type="text"
                        readonly
                        value=" {{data.cost}}"
                        id="optName{{i}}"
                      />
                    </div>
            </div>

here's the .TS

----- TS
 constructor(private builder: FormBuilder) {
    this.form = this.builder.group({
      qtyTotal: this.builder.control("", [
        Validators.required,
        Validators.min(1)
      ]),

      optionGroup: this.builder.array([]);
     });
  } //end constructor

1 Answer 1

1

You can initialize the form array in your class.

ngOnInit() {
  this.initFormArray();
}

initFormArray() {
    this.menuOptions.forEach(x => {
      (<FormArray>this.form.get("optionGroup")).push(
        this.builder.group({
          optionsQty: [null],
          optionsName: [x.name],
          optionsCost: [x.cost]
        })
      );
    });
  }

You got an issue because you try to access the empty form array in HTML.

updated solution.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.