对前端开发人员来说,表单是非常重要的,它负责用户与程序的交互。它承载着一部分数据校验的功能,以此减少服务端的压力。本篇文章就是对angular表单验证的两种方法进行介绍。
模板驱动验证
为了向模板驱动表单中添加验证,需要添加一些验证属性,这里就用户登录界面为例进行说明
一:新建项目
到工作路径下,运行ng new valicate创建一个angular项目,然后用vscode打开

二:修改app.component.html模板文件
创建一个表单,有两个输入框,分别为用户名和密码,接下来对这两个输入框进行验证
app.component.html
<br><br>
<p class="container-fluid">
<p class="row">
<p class="col-md-4">
</p>
<p class="col-md-4">
<h1 class="form-group">Login</h1>
<form role="form">
<p class="form-group">
<label for="exampleInputEmail1">
Email address
</label>
<input type="email" class="form-control" id="exampleInputEmail1" />
</p>
<p class="form-group">
<label for="exampleInputPassword1">
Password
</label>
<input type="password" class="form-control" id="exampleInputPassword1" />
</p>
<button type="submit" class="btn btn-primary">
Submit
</button>
</form>
</p>
<p class="col-md-4">
</p>
</p>
</p>代码中运用到的样式均为Bootstrap4中提供的css样式,读者可以到其官网下载。
最终的样式如下:

三:添加校验
首先在app.module.ts中,添加FormsModule模块,并增加到imports数组中
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }然后在模板页面中添加校验器
添加校验的app.component.html
<br><br>
<p class="container-fluid">
<p class="row">
<p class="col-md-4">
</p>
<p class="col-md-4">
<h1 class="form-group">Login</h1>
<form role="form">
<p class="form-group">
<label for="exampleInputEmail1">
Email address
</label>
<input type="email" class="form-control" id="exampleInputEmail1" [(ngModel)]="email" name="email"
#emailFC="ngModel" required/>
</p>
<p *ngIf="emailFC.invalid" class="alert alert-danger">
请输入邮箱地址!
</p>
<p class="form-group">
<label for="exampleInputPassword1">
Password
</label>
<input type="password" class="form-control" id="exampleInputPassword1" />
</p>
<button type="submit" class="btn btn-primary">
Submit
</button>
</form>
</p>
<p class="col-md-4">
</p>
</p>
</p>最终效果如下:

四:注意事项
在Input标签中必须添加name属性,且 #name 与ts中class的属性名称不能相同,如图

一:在app.module.ts中引用ReactiveFormsModule
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { StudentComponent } from './student/student.component';
@NgModule({
declarations: [
AppComponent,
StudentComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [
AppComponent
]
})
export class AppModule { }相关文章推荐:
javascript事件定义,绑定事件和事件驱动中的命令语言
以上就是Angular表单验证的两种方法介绍的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号