I am trying to create a complex reactive form with nested component that is populated with a data object.
The behavior I am trying to achieve is very similar to the two-way data binding of a template-driven form: when the user edits an input of the form, the data object is changing automatically.
but as opposed to template-driven form, I cannot use [(ngModel)]
because it is deprecated in reactive forms for angular V6.
I know that fromGroup.patchValue()
will only do a one way binding and then ill have to manually subscribe to change events and update the data object manually - this will result in a lot of tiring code.
Is there any workaround for that scenario?
Well if I understand you correctly I had a similar problem what I did (I really don't know if this is the best practice)but it's work for me so in the HTML:
<mat-form-field class="mat-container">
<input matInput [formControl]="generalDiscount" type="number"
formControlName="generalDiscount"
(input)="course.amounts.generalDiscount = $event.target.value" <-the workaround
placeholder="Discount" required="required">
</mat-form-field>
This input makes it two way binding and in your .ts class you need to put the same field in your form group like
this.amountGroup = this._formBuilder.group({
[this.course.amounts.fitToNomberOfPeople,Validators.required],
generalDiscount:[this.course.amounts.generalDiscount,Validators.required],
});
hope that helps