Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keeping two FormControl input elements in sync using ReactiveForms in angular 4

Given a component, with a form declaration

ngOnInit() {
  this.form = this.fb.group({
    address: [""],
  });
}

An two input controls on a form, both referencing the same control.

<input type="text" class="form-control" placeholder="Address" formControlName="address">
<input type="text" class="form-control" placeholder="Address" formControlName="address">

How do I keep the input values the same in each of the controls. Updating each input element does change the model value, but not the other corresponding input value. I am sure this is by design.

I am using the control on a tabbed interface, that requires a duplicate on each tab. Is there an easy way to keep them updated?

I have a working plunker demonstration.

like image 440
Jim Avatar asked Mar 21 '18 17:03

Jim


People also ask

Can we use ngModel and FormControl together in Angular?

Angular Form Controls and ngModels Don't mix.

Is reactive form synchronous?

Reactive forms are mostly synchronous in nature whereas, Template driven forms are asynchronous. Logic Driven Source: The template-driven approach draws logic from the template, whereas in reactive driven forms the logic resides mainly in the component or typescript code.

Can we use ngModel and formControlName together?

In short ngModel can't be used by itself within FormGroup When you use formControlName, ngModel does not activate or create a control (it's simply used as an @Input). formControlName just links to the existing input you created in your class.

Can we use FormControl without FormGroup?

Sometimes, we don't need a FormGroup, as our form might only consist of a single form control. Think of a search field that let's you search for products in an e-commerce application. Technically, we don't even need a <form> element for that.


1 Answers

just add a value field to the form

<input type="text" class="form-control" [value]="form.value.address" placeholder="Address" formControlName="address">
<input type="text" class="form-control" [value]="form.value.address" placeholder="Address" formControlName="address">

check out this plunker

like image 189
Obed Amoasi Avatar answered Nov 15 '22 16:11

Obed Amoasi