I am using Angular Control value accessor interface for reusable forms in my project. And I am facing a problem with setting values when building parent form.
Let'say I have an Address object that I want to map into the cva form and this object has more fields then the actual form does. So in the parent component I build the form:
constructor(private formBuilder: FormBuilder) {
const address = new Address({
id: 1,
city: 'Roma',
streetAddress: 'via Roma',
houseNumber: '12b',
postalCode: 43213,
addressType: 'abitazione',
addInfo: 'primo piano'
});
this.addressForm = this.formBuilder.group({
address: [address],
});
}
<form [formGroup]="addressForm" (ngSubmit)="submit()">
<app-address-cva formControlName="address"></app-address-cva>
<button>Sign Up</button>
</form>
and in the child component I process the values passed by parent:
writeValue(value: Address) {
if (value) {
this.value = value;
}
if (value === null) {
this.form.reset();
}
}
set value(value) {
this.cityControl.setValue(value.city);
this.streetAddressControl.setValue(value.streetAddress);
this.houseNumberControl.setValue(value.houseNumber);
this.postalCodeControl.setValue(value.postalCode);
this.onChange(value);
this.onTouched();
}
When submitting the form I don't get the value of the child cva form but the address object that was passed by the parent. This is in case if the form fields were not touched by the user. If any input of the child form is touched the subform returns the value of form controls and everything works just fine.
I have tried to use change detection, mark cva form fileds as touched and dirty programmatically inside the writeValue method, I have tried to call updateValueAndValidity({ onlySelf: false, emitEvent: true }) method even. But I could not solve this problem.
Here is the stackblitz project to show the exact problem: [https://stackblitz.com/edit/angular-ggepd6?file=src%2Fapp%2Fapp.component.ts]
I will be gratefull if someone could help me with this issue.