Cory Rylan

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

Follow @coryrylan
Angular

Syncing Multiple Reactive Form Inputs in Angular

Cory Rylan

- 1 minute

Updated

This article has been updated to the latest version Angular 17 and tested with Angular 16. The content is likely still applicable for all Angular 2 + versions.

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   
Twitter Facebook LinkedIn Email
 

No spam. Short occasional updates on Web Development articles, videos, and new courses in your inbox.

Related Posts

Angular

Creating Dynamic Tables in Angular

Learn how to easily create HTML tables in Angular from dynamic data sources.

Read Article
Web Components

Reusable Component Patterns - Default Slots

Learn about how to use default slots in Web Components for a more flexible API design.

Read Article
Web Components

Reusable Component Anti-Patterns - Semantic Obfuscation

Learn about UI Component API design and one of the common anti-patterns, Semantic Obfuscation.

Read Article