Ranjith Varadan Ranjith Varadan - 10 months ago 82
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 class="form-group">
<label for="">Last Name</label>
<input type="text" class="form-control" formControlName="lastname" [(ngModel)]="secondnamename">
<div class="form-group">
<label for="">Display Name</label>
<input type="text" class="form-control" formControlName="displayname" value='{{firstname}}{{lastname}}'>
<div class="margin-20">
<div>myForm details:-</div>
<pre>myForm value: <br>{{myForm.value | json}}</pre>

Here is my plnkr


enter image description here

Answer Source

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