Cory Rylan

My name is , Software Developer and Speaker. Building Design Systems and Web Components.

Follow @coryrylan
Angular

Syncing Multiple Reactive Form Inputs in Angular

By Cory Rylan

- 1 minute

Updated

Angular APIs may have changed since this article was published. Check the current Angular documentation when using its examples.

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!

View Demo Code   
Bluesky Facebook LinkedIn Email
 

Related Posts

Angular

Angular ngFor syntax

A introduction tutorial on how to use the Angular ngFor syntax in component templates to construct lists dynamically.

Read Article
Angular

Angular Observable Data Services

A tutorial on how to use Observables and how they can improve your Angular data services and managing state in your applications.

Read Article
Angular

Angular Form Builder and Validation Management

Learn about the new FormBuilder service and create a custom component to manage form validation in Angular components.

Read Article