0
votes

I have many many input need to be validated. So I use reactive form to validate them. For example,

<input formControlName="testName">

In the constructor I defined the nested form.

constructor(private fb: FormBuilder) {
   this.totalForm = this.fb.group({
       'subForm': this.fb.group({
           testName: [null, Validators.required]
       // ....
      })
   });
}

When I submit the data to the server, I want to use the fresh data from the input field. But I found the form control's data was not updated. The reason is that the form can't be two way binding unless using ngModel.

  this.dataTobeSubmited = this.totalForm.controls['subForm'].controls['testName'].value;

I use Angular 5, of course I can add ngModel. However if in the future we upgrade to the high version, it will becomes a problem since

Using Reactive Froms with ngModel is deprecated in angular 6 and is removed in angular 7

My case is a nested reactive forms, is there a better way to do two way binding?

UPDATE For my binding

The binding for the nested form group sample.

<form [formGroup]="profileForm">
 <app-child [subForm]="profileForm.controls['subForm']"></app-child>
       <button (click)="whatIsTheFormValue()"> What Is My Value?</button>
 </form>

https://stackblitz.com/edit/angular-9dzabi

Am I right?

2
A more complete example might help us narrow down the issue. Also, for clarification, are you accessing the form group's value (this.totalForm.value), and it's value is not the most current one? - John Gallego
this.totalForm.value.subForm.testName, and NO, not add [(ngModel)] even in Angular 6 - Eliseo

2 Answers

0
votes

There are 2 solutions for this.

  1. A listener to any changes within the form. This FormGroup.valueChanges may be what you need.

    Basically, the flow would be having a subscription to this.totalForm.valueChanges. Inside this subscription you can react on any changes from any input. Since this is an observable, you can also use operators such as distinctUntilChanged or debounce.

  2. Have the submit button kick off a function, which grabs the form data via this.totalForm.getRawValue().

Hope it helps.

-1
votes

u dont need ngModel. use this.totalForm.value to see the current value of your form.