简体   繁体   中英

Two Way (Double) Binding in Angular Model Driven Reactive Forms

Here's an interface:

interface User { name: string; }

and a reactive form:

 ngOnInit() { this.formGroup = this.fb.group({ name: [user.name, Validators.required] }); } 
 <form [formGroup]="formGroup" novalidate> <input type="text" formControlName="name"> </form> 

Is there a way to have the value of user.name get updated automatically (two-way binding just like template-driven ngModel ) when the input field gets updated?

It's possible.

At first you need to import the FormsModule next to the ReactiveFromsModule to your project.

And add [(ngModel)]="name" to your html, it looks like following:

<form [formGroup]="formGroup">
    <input type="text" [(ngModel)]="name" formControlName="test">
</form>

See this plunkr .

Update model via subscription: You can subscribe to the formGroup valueChange and edit your model respectively.

Like this way:

  this.formGroup.valueChanges.subscribe((changes) => {
    this.submitObj = changes;

    for(let propName in changes){
      this.test[propName] = changes[propName];
    }
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM