Two way binding in reactive forms

丶灬走出姿态 提交于 2019-11-30 10:42:35

Note: as mentioned by @Clouse24, "Using Reactive Froms with ngModel is deprecated in angular 6 and will be removed in angular 7" (which means that the answer below will no longer be supported beginning version 7). Please read the link to see the reasoning for deprecation and to see what alternatives you will have.

You can use [(ngModel)] with Reactive forms.

<form [formGroup]="form">
  <input name="first" formControlName="first" [(ngModel)]="example.first"/>
  <input name="last" formControlName="last" [(ngModel)]="example.last"/>
</form>

export class App {
  form: FormGroup;
  example = { first: '', last: '' };

  constructor(builder: FormBuilder) {
    this.form = builder.group({
      first: '',
      last: ''
    })
  }
}

Plunker

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.

Sometimes you might need to combine [(ngModel)] with Reactive forms. I could be some inputcontrol that you don't need as a part of the form, but you still need it to be binded to the controller. Then you can use: [(ngModel)]="something" [ngModelOptions]="{standalone: true}"

Here is how you can solve it:

In order to have the result of two-way-binding

I use local "template variables" and use the same formControl for both fields.

<form [formGroup]="formGroup">
  <input #myInput (input)="mySlider.value = myInput.value" type="number" formControlName="twoWayControl">

  <mat-slider #mySlider (input)="myInput.value = mySlider.value" formControlName="twoWayControl" min="1" max="100">
  </mat-slider>

</form>

When I programmatically want to change the value of the model I use setValue() as others have proclaimed.

setTo33() {
  this.formGroup.get('twoWayControl').setValue(33);
}

If you just want to show a input value just create a variable in your input and use in your template.

... lots of other inputs
    <h4>Example values: {{ name.value }}</h4>
// Allow two way binding on the [(name)] from the parent component
private nameValue: string;
@Input()
get name() {
    return this.nameValue;
}
set name(values) {
    this.nameValue = values;
    this.nameChange.emit(this.nameValue);
}
@Output() nameChange = new EventEmitter<string>();

ngOnInit() {
    // Update local value and notify parent on control value change
    this.formControl.valueChanges.forEach(value => this.name = value));
}

ngOnChanges() {
    // Update local value on parent change
    this.formControl.setValue(this.expression);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!