在很多常见的 Web 应用中,使用表单处理用户输入,是非常重要的功能。Angular 框架提供了两种方式处理用户输入:
- 模板式表单
- 响应式表单
这两种方式的表单,都会捕获用户输入事件,验证用户输入的数据,创建表单模型和数据模型,并跟踪数据的变化。
下面,我们介绍如何使用 Angular 的模板式表单,创建一个登录组件。
模板式表单
在 Angular 10 应用中,我们可以使用 FormsModule
创建一个模板式表单。
- 在 AppModule 模块中,导入
FormsModule
.
import { BrowserModule } from '@angular/platform-browser’;
import { NgModule } from '@angular/core’;
import { FormsModule } from "@angular/forms”;
import { AppComponent } from './app.component’;
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- 创建一个登录组件。
ng generate component login
- 修改登录组件模板,添加登录表单的标签元素。
<form>
<div>
<input type="text" name="username" placeholder=“Username”>
</div>
<div>
<input type="password" name="password" placeholder=“Password”>
</div>
<button type="submit">Login</button>
</form>
- 修改登录组件类,添加两个属性。
…
export class LoginComponent implements OnInit {
username: string;
password: string;
…
}
- 修改登录组件模板文件,为每个
input
标签元素添加ngModel
指令,并绑定到组件类的属性。
<form>
<div>
<input type="text" name="username" placeholder="Username" [(ngModel)]=“username”>
</div>
<div>
<input type="password" name="password" placeholder="Password" [(ngModel)]=“password”>
</div>
<button type="submit">Login</button>
</form>
- 修改登录组件类,添加一个
login
方法。
login() {
console.log('User: ' + this.username);
console.log('Password: ' + this.password);
}
- 修改登录组件模板文件,绑定
login
方法到ngSubmit
事件。
<form (ngSubmit)="login()”>
…
</form>
- 打开
src/app/app.component.html
文件,删除所有内容,添加下面的指令:
<app-login></app-login>
运行效果
运行项目,打开浏览器访问首页,键入用户名和密码后,点击登录按钮,控制台会输出刚刚输入的用户名和密码信息。

网友评论