Syncing Multiple Reactive Form Inputs in Angular
When it comes to complex form UIs occasionally, we can run into a situation where we want to keep two user inputs in sync with each other. Sometimes this happens when we are showing and hiding an input displayed in different parts of the UI dependent on certain conditions or business rules. In this short post, we will see how we can keep as many inputs in sync with the same value using Angular's Reactive Forms API
In our use case, we will sync three inputs to the same form value. First, we need to create our form using the Reactive Forms API. We could use the FormBuilder
Service or the FormControl
class to create our form inputs. For this use case, we will use the FormControl
class. We create our single form control by instantiating an instance of the FormControl
class.
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
search = new FormControl('hello');
}
In our template we can bind multiple inputs to a single Form Control instance. We simply reference the form control name for each input bound to it. To keep the controls in sync we can set the value property of the form control to the search
Form Control instance. Every time the Form Control is updated the search.value
will be passed back to each input.
<h1>Keeping multiple reactive form controls in sync</h1>
<input placeholder="search 1" [formControl]="search" [value]="search.value" />
<input placeholder="search 2" [formControl]="search" [value]="search.value" />
<input placeholder="search 3" [formControl]="search" [value]="search.value" />
Check out the full working demo below!