Ranjith Varadan Ranjith Varadan - 9 days ago 6
TypeScript Question

Two way data binding in model driven forms

I have a reactive form, in which, i have a first name, a last name and finally display name textbox. When i give first name and last name, the value of the display name textbox should contains first name and second name concatenated. But as i'm still in learning stage, couldn't able to figure out what is wrong with this code. Any advice would be helpful. Thank you.

Here is my code

<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)">
<div class="form-group">
<label for="">First Name</label>
<input type="text" class="form-control" formControlName="firstname" [(ngModel)]="firstname">
</div>
<div class="form-group">
<label for="">Last Name</label>
<input type="text" class="form-control" formControlName="lastname" [(ngModel)]="secondnamename">
</div>
<div class="form-group">
<label for="">Display Name</label>
<input type="text" class="form-control" formControlName="displayname" value='{{firstname}}{{lastname}}'>
</div>
<div class="margin-20">
<div>myForm details:-</div>
<pre>myForm value: <br>{{myForm.value | json}}</pre>
</div>
</form>


Here is my plnkr

Gif:

enter image description here

Answer

You can also take the more "reactive" approach and listen to changes of the form like:

   this.myForm.valueChanges.subscribe((form) => {
     this.displayname = `${form.firstname} ${form.secondname}`;
   });

Then you can even get rid of the unnecessary two-way data-binding (and the corresponding local state) you use for firstname and secondname like that. See the Plunker: https://plnkr.co/edit/h5aFRDTWfj0gQ69CvVK7?p=preview

Comments