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?
We can perform Two way binding in Template driven forms but there is no two way binding in Reactive forms. Angular provides the methods to update the values from the component class. Reactive forms are used on complex cases, like dynamic forms element, dynamic validations etc.
You can use [(ngModel)] with Reactive forms. This will a completely different directive than the one that would be used without the formControlName . With reactive forms, it will be the FormControlNameDirective . Without the formControlName , the NgModel directive would be used.
The two-way data binding in Angular is used to display information to the end user and allows the end user to make changes to the underlying data using the UI. This makes a two-way connection between the view (the template) and the component class. This is similar to the two-way binding in WPF.
Angular v2+ supports two-way data binding using ngModel directive and also by having getter and setter methods.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With