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>
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);