跳到正文
本页尚未翻译成中文,以下为英文原文。 查看英文版

Forms Overview ​

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 set up a form using a template-driven approach.


1. Create an input field ​

In user.ts, update the template by adding a text input with the id set to framework, type set to text.

html
<label for="framework">
  Favorite Framework:
  <input id="framework" type="text" />
</label>

2. 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 the imports array of the User.

ts
import {Component} from '@angular/core';
import {FormsModule} from '@angular/forms';

@Component({
...
imports: [FormsModule],
})
export class User {}

3. Add binding to the value of the input ​

The FormsModule has a directive called ngModel 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 the favoriteFramework property.

html
<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!

基于 MIT 许可证发布。