SteGriff

Blog

Next & Previous

Angular Binding Two Controls To One Form Value

Angular! It makes some of the most complex things slightly simpler but boy oh boy, it makes the simplest things exceptionally hard.

A thing you could do

In Vue (or ol’ AngularJs) you can do this:

<input v-model="message" placeholder="Your Message">
<input v-model="message" placeholder="Your Message Again">
<p></p>

As you type in the first field, it’ll appear in the second field and the p tag. And vice versa if you type in the second field. All the fields bound to the same value synchronise.

But in Angular

In Angular, we use FormControls for this stuff, or any kind of “dynamic forms” really. So you’d think we could do this TypeScript:

yourName: FormControl = new FormControl('');

and this HTML:

<input [formControl]="yourName" placeholder="Name">
<input [formControl]="yourName" placeholder="Name Again">
<p>Value of Name: </p>

And they’d bind together, right?

But it doesn’t work! Here’s a demo.

So here’s the stupid hack

Of course, you can “just” add this crazy subscribe statement to your ngOnInit that makes the field subscribe to… itself…

this.yourName.valueChanges.subscribe(value => {
  this.yourName.setValue(value, {
	onlySelf: true, emitEvent: false, emitModelToViewChange: true
  });
}, error => { }, () => { });

That’s it

I haven’t tried banana-in-a-box, maybe that would work in a predictable way? But since we’re really clearly pushed in the direction of using FormControls in Angular, why doesn’t this Just Work?

The end of another fine rant. Have fun!