Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way binding on angular 6 reactive form

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?

like image 847
Idan Abrashkin Avatar asked May 16 '18 12:05

Idan Abrashkin


People also ask

Can we use two way data binding in Reactive form?

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.

Can we use ngModel inside Reactive form?

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.

What is 2 way data binding in Angular?

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.

Does angular2 support 2 way binding?

Angular v2+ supports two-way data binding using ngModel directive and also by having getter and setter methods.


1 Answers

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

like image 140
oren Avatar answered Oct 13 '22 20:10

oren