Forms are a big part of many apps because they enable your app to accept user input. Let's learn about how forms are handled in Angular.
In Angular, there are two types of forms: template-driven and reactive. You'll learn about both over the next few activities.
In this activity, you'll learn how to setup a form using a template-driven approach.
-
Create an input field
In
user.component.ts
, update the template by adding a text input with theid
set toframework
, type set totext
.<label for="framework"> Favorite Framework: <input id="framework" type="text" /></label>
-
Import
FormsModule
For this form to use Angular features that enable data binding to forms, you'll need to import the
FormsModule
.Import the
FormsModule
from@angular/forms
and add it to theimports
array of theUserComponent
.import {Component} from '@angular/core';import {FormsModule} from '@angular/forms';@Component({ ... imports: [FormsModule],})export class UserComponent {}
-
Add binding to the value of the input
The
FormsModule
has a directive calledngModel
that binds the value of the input to a property in your class.Update the input to use the
ngModel
directive, specifically with the following syntax[(ngModel)]="favoriteFramework"
to bind to thefavoriteFramework
property.<label for="framework"> Favorite Framework: <input id="framework" type="text" [(ngModel)]="favoriteFramework" /></label>
After you've made changes, try entering a value in the input field. Notice how it updates on the screen (yes, very cool).
Note: The syntax
[()]
is known as "banana in a box" but it represents two-way binding: property binding and event binding. Learn more in the Angular docs about two-way data binding.
You've now taken an important first step towards building forms with Angular.
Nice work. Let's keep the momentum going!