CodexBloom - Programming Q&A Platform

Angular 15 - how to Bind FormArray Values to Template with Reactive Forms

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-06-03
angular reactive-forms formarray TypeScript

I'm currently working with Angular 15 and working with a frustrating scenario when trying to bind a `FormArray` to my template using reactive forms. I have a form set up to dynamically add multiple items, but while the form inputs update correctly, the values aren't reflecting back in the template. Here's a simplified version of my component code: ```typescript import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; @Component({ selector: 'app-dynamic-form', templateUrl: './dynamic-form.component.html' }) export class DynamicFormComponent implements OnInit { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ items: this.fb.array([]) }); } ngOnInit() { this.addItem(); // Start with one item } get items(): FormArray { return this.myForm.get('items') as FormArray; } addItem() { this.items.push(this.fb.control('')); } } ``` And here's my template: ```html <form [formGroup]='myForm'> <div formArrayName='items'> <div *ngFor='let item of items.controls; let i = index'> <input [formControlName]='i' /> </div> </div> <button (click)='addItem()'>Add Item</button> </form> <p>Values: {{ myForm.value.items | json }}</p> ``` In the template, I expect to see the values of the `FormArray` displayed in the paragraph below the form. However, when I type in the input fields, the displayed values don't update dynamically. I’ve also checked that the form is valid and there are no errors in the console. I’ve tried using `ChangeDetectorRef.detectChanges()` after adding items, but it didn’t resolve the scenario. Additionally, I confirmed that there are no issues with Angular's change detection strategy; I’m not using `OnPush` anywhere in my component. Could anyone point out what might be going wrong here? I'm sure I'm missing something simple, but I need to figure it out. Any help would be appreciated!