Two way binding on angular 6 reactive form

蹲街弑〆低调 提交于 2019-12-05 01:41:54
oren

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

Some kind of workaround.

Proposition is to use (input) event. formControl1 updates own value and writes its value to formControl2 with additional '@example.com' text also. Changing formControl2 value updates own value and updates formControl1 with striped '@example.com' text.

import { Component } from '@angular/core';
import {FormControl} from '@angular/forms';

@Component({
  selector: 'app-template-and-reactive-form',
  template: '<input #inp1 [ngModel]="formControl1.value" ' +
    '(input)="formControl1.setValue(inp1.value);formControl2.setValue(inp1.value+\'@example.com\')" ><br>\n' +
    '<input #inp2 [ngModel]="formControl2.value" ' +
    '(input)="formControl2.setValue(inp2.value);formControl1.setValue(inp2.value.replace(\'@example.com\',\'\'))"><br>\n' +
    'formControl1 value: {{formControl1.value}}<br>\n' +
    'formControl2 value: {{formControl2.value}}<br>',
  styleUrls: ['./template-and-reactive-form.component.scss']
})
export class TemplateAndReactiveFormComponent  {
  formControl1 = new FormControl('');
  formControl2 = new FormControl('');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!