Reputation: 3689
I have an Angular Reactive Form with validation.
What's the proper way to invoke the setter for my hiddenComposedField
?
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); // :(
}
<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
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
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
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