Angular reactive forms: sync multiple inputs with a single formControlName
Asked Answered
R

1

8

I'm building a reactive form in Angular 11. It's split up across multiple divs, and the project owner wants a few repeated inputs in each of those divs so that a user can edit an input for some field A, and all of the divs' inputs for field A will show the updated value.

I like corylan's approach:

<input [formControl]="myCtrl" [value]="myCtrl.value" />
<input [formControl]="myCtrl" [value]="myCtrl.value" />
<input [formControl]="myCtrl" [value]="myCtrl.value" />

...but I want to achieve this with formControlName instead of formControl so that I can take advantage of formGroups (and not have each form control be a member of my component object). However, lacking a reference to the the actual myCtrl would ruin the binding at [value].

Is there a good strategy for me to specify the form control by name only and have all of these inputs use a single control? Or is there a different good way to sync inputs in Angular reactive forms when there are quite a few different sets to sync?

Rubie answered 12/7, 2021 at 13:10 Comment(2)
I you can try it with FormArraySherburn
@Sherburn kind of, but there are two problems: (1) unless I'm working with inputs that lend themselves to an array, the use of of FormArray would make the surrounding component brittle. (If I ever need to add or remove an element, the indicies for all subsequent elements needs to be changed. And if one of our html/css guys adds/removes an input, he's going to have no idea why everything broke, and (2) my ng app still wouldn't compile because my inputs exist before some of the controls.Rubie
B
9

This can be achieved by setting value to the forms controls actual value.

<form [formGroup]="searchForm">
  <input placeholder="search" formControlName="search" [value]="searchForm.value.search" />
  <input placeholder="search" formControlName="search" [value]="searchForm.value.search" />
  <input placeholder="search" formControlName="search" [value]="searchForm.value.search" />
</form>

STACKBLITZ: https://stackblitz.com/edit/angular-y6gxf6?file=src%2Fapp%2Fapp.component.html

Bain answered 12/7, 2021 at 13:34 Comment(1)
Good answer. I would add that you can also use searchForm.value.search for the value property.Kasey

© 2022 - 2024 — McMap. All rights reserved.