Search code examples
angularangular-reactive-formsangular11

Angular reactive forms: sync multiple inputs with a single formControlName


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?


Solution

  • 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