0

I am using Angular reactive form and need to set the value of a Full Name form control by using the values of First Name and Last Name. I have the code as follows :

<form [formGroup]="personForm">
    <input type="text" formControlName="first_name" maxlength="255">
    <input type="text" formControlName="last_name" maxlength="255">
    <input type="text" formControlName="full_name" maxlength="255">
</form>

and the form is defined as :

this.personForm = this.formBuilder.group({
    first_name: [_.get(person, 'first_name', ''),Validators.required],
    last_name: [_.get(person, 'last_name', ''),Validators.required],
    full_name: [_.get(person, 'display_name', ''),Validators.required]
 });

I would like to generate the full_name value as the combination of first_name and last_namewhen clicking on the full_name input field. How can this be possible ?

Happy Coder
  • 4,255
  • 13
  • 75
  • 152
  • Does this answer your question? [How to set value to form control in Reactive Forms in Angular](https://stackoverflow.com/questions/55275025/how-to-set-value-to-form-control-in-reactive-forms-in-angular) – Kaustubh Khare Jul 31 '20 at 17:06
  • But how can I generate the combined value of change or on focus ? – Happy Coder Jul 31 '20 at 17:09
  • you can use `blur` output event. Add `(blur)="function"` on both the input box and concat the values into the `function`. https://angular.io/guide/user-input#on-blur – Kaustubh Khare Jul 31 '20 at 17:11

3 Answers3

0

Try this

<form [formGroup]="personForm">
    <input #input1 type="text" formControlName="first_name" maxlength="255">
    <input #input2 type="text" formControlName="last_name" maxlength="255">
    <input type="text" formControlName="full_name" maxlength="255" value="{{input1.value}} {{input2.value}}">
</form>
  • Will this approach update the value into `full_name` variable as well? – Kaustubh Khare Jul 31 '20 at 17:18
  • Yes, but if this is insert form You no need show a user this data on submit form join value to fullname in code behind and save it in data base, next when You want to show in this meaner only get one value from db and show it in some field or label, i think –  Jul 31 '20 at 17:30
0

what do you think can this help you?

Demo: https://angular-formgroup-vsdjkc.stackblitz.io

In the example, I use the formGroup valueChanges to listen all of the form changes.

And just do the patchValue with the updated first name and last name

Ashot Aleqsanyan
  • 4,252
  • 1
  • 15
  • 27
0

I have tried with blur and patchValue. Please check the below demo link.

blur - On focus change it will call function, concate the first_name and last_name value stores into full_name.

patchValue - it will update value into full_name and displays into form.

blur demo

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48