3

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>
0

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.