...

/

Understanding Two-Way Data Binding and Reactive Forms in Angular

Understanding Two-Way Data Binding and Reactive Forms in Angular

Learn about the two-way data binding process in Angular using template forms and Reactive forms.

When building single-page applications, we will often need a user to input data of some sort using a form. Angular uses a two-way data binding process to bind values that are entered on a form to variables within a component itself. This process is two-way because Angular will take care of synchronizing what is shown in the DOM with the member variables of a component. So, if we change a value programmatically within our code, this value will be updated in the HTML. Similarly, when a user modifies the HTML values, these values will automatically update our class member variables.

Angular actually has two different methods of creating two-way data binding forms:

The first method is named template forms, which allows us to bind an input control directly to a property on our class.

<input type="text" [(ngModel)]="name" /> 

Here, we have an input control within our HTML template, which uses the [(ngModel)] attribute with a value of "name".

This tells the Angular runtime that it must synchronize the input value of this control with a property named "name" on the component class as follows:

Press + to interact
@Component({
... selectors
})
export class SampleComponent {
name: string = "";
}

Here, we have an Angular component named SampleComponent with a property named name. Again, if we set this value within our component class, then the value will be shown within the HTML template, and if we modify the value from the HTML template, this property will automatically be updated.

While template forms are very simple to implement, they do have limitations. As an example, we may want to show or hide certain form fields depending on a selection that the user has made. We may also wish to provide extra validation on the input, say, to ensure that the user has entered a ...