How can I bind a form to a model in Angular 6 using reactive forms?

angular 7 reactive forms two-way binding
can 't bind to 'formgroup' since it isn 't a known property of 'form
angular reactive forms set value
angular reactive forms example
angular reactive forms validation
angular 6 form submit example
form control angular
angular 8 reactive forms

Prior to angular 6, I was using [(ngModel)] to directly bind my form field to the model. This is now deprecated (can't use with reactive forms) and I am not sure how to update my model with the form values. I could use form.getRawValue() but this would require me to replace my current model with the new rawValue - this is not favourable since my main model is larger and has more fields than the local form model.

Any ideas?


If you're binding to a form control like a text input, use this syntax like you would any other reactive form:

<ng-container [formGroup]="this.myFormGroup">
    <input type="text" formControlName="field1">
    <input type="text" formControlName="field2">
    <ng-container formGroupName="subgroupName">
        <input type="text" formControlName="subfield2">
    </ng-container>
</ng-container>

In your component class, in constructor() (should be before the template renders), use the following syntax to build a form group to talk to this form:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

...
    public readonly myFormGroup: FormGroup;
...
    constructor(private formBuilder: FormBuilder) {
        this.myFormGroup = this.formBuilder.group({
            field1: [],
            field2: [],
            subgroupName: this.formBuilder.group({
                subfield2: [],
            }),
        });
        this.retrieveData();
    }

If your component needs to retrieve data from a service as it loads, you must make sure it starts the transfer after the form has been built, then use patchValue() to put the data from your object into the FormGroup:

    private retrieveData(): void {
        this.dataService.getData()
            .subscribe((res: SomeDataStructure) => {
                // Assuming res has a structure like:
                // res = {
                //     field1: "some-string",
                //     field2: "other-string",
                //     subgroupName: {
                //         subfield2: "another-string"
                //     },
                // }
                // Values in res that don't line up to the form structure
                // are discarded. You can also pass in your own object you
                // construct ad-hoc.
                this.myFormGroup.patchValue(res);
            });
    }

Read-only data bindings to the model of the FormGroup are accessed a little differently:

{{ this.myFormGroup.get('field1').value }}
{{ this.myFormGroup.get('subgroupName.subfield2').value }}
<!-- Hint: use an array if you have field names that contain "." -->
{{ this.myFormGroup.get(['subgroupName', 'subfield2']).value }}

All these techniques eliminate the need for any [(ngModel)] bindings.

Reactive forms, The instantaneous two-way data binding of ng-model in Angular 1 is really a life-​saver as it allows to transparently keep in sync a form with a  What we do with reactive forms instead, is keeping the data in the form model, until the user hits the submit button. Only then the data is copied over to the original model, replacing everything. This type of overwriting everything is called "immutable objects". Form Controls. To create this form-model, angular uses a class called FormGroup.


As explained more fully in the Angular Documentation, with reactive forms, you do not bind the form directly to your model. Rather, you use a FormBuilder to build a FormGroup object (essentially, "the form") that will maintain it's own model. During construction, you have the opportunity to set initial values in the form, which you would usually do from your model.

You then bind form controls in your template to the form's model. User interaction with the form controls updates the form's model.

When you are ready to do something with the form data (e.g. "submit" the form), you can get the values from the form fields by using either the FormGroup's value property or it's getRawValue() method - these two behave differently, see the documentation for details.

Once you get the values from the form, if you wish, you can update your model with the values from the form.

Angular Forms Guide: Template Driven and Reactive Forms, To use reactive forms, we need to import the ReactiveFormsModule into our parent module. In our case, the parent But binding to the model directly comes with one large downside. To create this form-model, angular uses a class called FormGroup. To define benn solomon danny king leo6 months. angular reactive forms - bind input element to reactive form programmatically 0 How to change value of a form-control on value-change of another form-control in Angular Reactive forms?


You can subscribe to changes in your form group and use it to update your model. But this is not safety. Because you must ensure that your form fields match the model fields or add verification that the fields in the model exist.

bindModelToForm(model: any, form: FormGroup) {
    const keys = Object.keys(form.controls);
    keys.forEach(key => {
        form.controls[key].valueChanges.subscribe(
            (newValue) => {
                model[key] = newValue;
            }
        )
    });
}

Full code of my service: referenceFields - means if you have complex fields like student: { name, group } where group is a referenced model, and you need to be able to get only id from this model:

import { Injectable } from '@angular/core';
import { FormGroup } from "@angular/forms";

@Injectable({
    providedIn: 'root'
})
export class FormService {

    constructor() {
    }

    bindModelToForm(model: any, form: FormGroup, referenceFields: string[] = []) {
        if (!this.checkFieldsMatching(model, form)) {
            throw new Error('FormService -> bindModelToForm: Model and Form fields is not matching');
        }
        this.initForm(model, form);
        const formKeys = Object.keys(form.controls);
        formKeys.forEach(key => {
            if (referenceFields.includes(key)) {
                form.controls[key].valueChanges.subscribe(
                    (newValue) => {
                        model[key] = newValue.id;
                    }
                )
            } else {
                form.controls[key].valueChanges.subscribe(
                    (newValue) => {
                        model[key] = newValue;
                    }
                )
            }
        });
    }

    private initForm(model: any, form: FormGroup) {
        const keys = Object.keys(form.controls);
        keys.forEach(key => {
            form.controls[key].setValue(model[key]);
        });
    }

    private checkFieldsMatching(model: any, form: FormGroup): boolean {
        const formKeys = Object.keys(form.controls);
        const modelKeys = Object.keys(model);
        formKeys.forEach(formKey => {
            if (!modelKeys.includes(formKey)) {
                return false;
            }
        });
        return true;
    }
}

Model-Driven Forms • Angular, When we talk about “reactive” forms (also known as model-driven), we'll In a sense, instead of binding Object models to directives like template-driven forms, we in fact The base form structure that we'll be using to implement our reactive form: 6. 7. <!DOCTYPE html>. <html>. <head>. <base href="." />. i have used reactive forms in my application and binding to html using formcontrolName. But now instead of declaring the properties inside the formbuilder, i need to call a model and assign that model to the formbuilder and use it in html. I been through many links but didnt find anywhere how to work based on my requirement. HTML:


Reactive Forms with Angular [Using easy Examples], In this blog post we will explore model driven forms using Angular's 6. export class User {. firstName: string;. lastName: string;. role: string; Creating an Angular Reactive Form with FormGroup, FormControl and FormBuilder and various form directives, we will bind our userForm to our template with  It’s a pretty standard barebones class that we can use to demonstrate binding data between objects and forms. Creating an Angular Reactive Form with FormGroup, FormControl and FormBuilder. In Angular, a reactive form is a FormGroup that is made up of FormControls.


Angular Form Fundamentals: Reactive Forms, Angular 2's latest forms module lets us build model-driven forms easily. building model-driven form with validation using the latest forms module, then bootstrap/3.3.6/ @angular/forms npm package and import the reactive forms module in We make sure we bind formGroup to our myForm property in  The instantaneous two-way data binding of ng-model in Angular 1 is really a life-saver as it allows to transparently keep in sync a form with a view model. Forms built with this directive can only be tested in an end to end test because this requires the presence of a DOM, but still, this mechanism is very useful and simple to understand.


Angular Reactive Forms Tutorial, decorator based validation in the reactive form via the model object. binding and validate nested FormGroup and FormArray in Angular. The FormControl class is the basic building block when using reactive forms. To register a single form control, import the FormControl class into your component and create a new instance of the form control to save as a class property.