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?

2
  • I you can try it with FormArray Commented Jul 12, 2021 at 13:16
  • 1
    @akkonrad 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. Commented Jul 12, 2021 at 13:27

1 Answer 1

10

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

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

2 Comments

Good answer. I would add that you can also use searchForm.value.search for the value property.
Great! Searched a lot to have such an easy answer!

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.