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?
There are 2 solutions for this.
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
.
this.totalForm.getRawValue()
.Hope it helps.