JJ Zabkar
JJ Zabkar

Reputation: 3689

Angular Reactive Form Programmatic Setter

I have an Angular Reactive Form with validation. What's the proper way to invoke the setter for my hiddenComposedField?

component.ts

ngOnInit() {
  this.myForm = this.formBuilder.group({
    'field1': ['', [Validators.required]],
    'field2': ['', [Validators.required]],
    'hiddenComposedField': [''],
  });

  this.myForm.get('field1').valueChanges.subscribe((val) => {
     this.setHiddenComposedField();
  });
  this.myForm.get('field2').valueChanges.subscribe((val) => {
     this.setHiddenComposedField();
  });
}

setHiddenComposedField() {
    let field1 = this.myForm.get('field1').value;
    let field2 = this.myForm.get('field2').value;

    // This doesn't work, but I want something like it:
    this.myForm.set('hiddenComposedField',field1 + ' ' + field2); // :(
}

component.html

<form [formGroup]="myForm">
  <input formControlName="field1">
  <input formControlName="field2">
  <!-- NB: hiddenComposedField is not exposed to the user; -->
  <!--     it is only on the submitted form model. -->
  <button type="submit">Submit</button>
</form>

Upvotes: 3

Views: 3109

Answers (3)

Ahmet Emrebas
Ahmet Emrebas

Reputation: 945

The ultimate solution for this problem is to subscribe the valueState of the form controls.

import { combineLatest } from 'rxjs';
const firstName = new FormControl();
const lastName = new FormControl();
const fullName = new FormControl();

combineLatest([firstName.valueChanges, lastName.valueChanges])
        .subscribe(([firstName, lastName]) => 
                     fullName.setValue(firstName + " " + lastName)
); 

firstName.setValue('Ahmet');
lastName.setValue('Emrebas');
   
console.log(fullName.value); // OUTPUT : Ahmet Emrebas
     

Whenever you change the values in the form, the c field will be updated automatically.

This is the most proper way to solve such a problem.

Upvotes: 0

user2243747
user2243747

Reputation: 2967

Slightly different way using string interpolation

setHIddenField(){
 const field1 = this.myForm.get('field1').value;
 const field2 = this.myForm.get('field2').value;
 const separator= ' --- ';
 let result = `${field1} ${separator} ${field2}`;
 this.myForm.get('hiddenComposedField').setValue(result);
}

Here is the StackBlitz link.

Upvotes: 0

Armin Smajovic
Armin Smajovic

Reputation: 56

Something like this should work so that you are getting the Control first and then setting its value.

this.myForm.get('hiddenComposedField').setValue(field1 + ' ' + field2);

Upvotes: 4

Related Questions