angularjs2 学习笔记(六) Form
Angular 2 Form表单
在angular2 form表单中我们需要了解表单数据绑定、数据验证、数据提交等内容,在下面的示例中并没有实际提交到后台,这部分内容在今后webapi中加以练习。
表单建立
<form (ngSubmit)="onSubmit(planetForm.value)" #planetform="ngForm">
</form>
这里是一个空的表单ngSubmit是一个事件,用于提交数据,数据则是整个form表单的内容,通常情况下我们的表单会绑定到我们的一个model中,那么提交的数据最后也是以json格式返回到后台来处理。
在表单中我们可以使用标准的html5控件来处理用户输入。
数据绑定
<div class="form-group">
<label class="col-xs-4 control-label" for="id">id : </label>
<div class="col-xs-8">
<input type="text" style="width: 300px" class="form-control" required
[(ngModel)]="myPlanet.id"
ngControl="id"
#planetid="ngForm">
<div [hidden]="planetid.valid || planetid.pristine" class="alert alert-danger">
The Name of green car is required !
</div>
</div>
</div>
这个一个表单输入的内容其中使用的是bootstrap的表单样式,在input中我们使用[(ngModel)](注意大小写)实现双向绑定,ngControl用于检测数据变化对应的是model中的字段,设置input的变量为ngForm来告诉angular 这个输入是这个表单内容。在vs中由于默认设置在粘贴html文本时会自动将大写字母变化成小写字母,所以angular的某些标签很容易发生错误,所以需要关闭这个自动转换,方法就是在vs的选项中将文本编辑器中的html高级选项下的粘贴时设置格式设置为false。
数据验证
html5内置的数据验证包括Required、minLength、maxLength、pattern ,我们可以将这些标签应用到我们的输入控件上,如
<input type="text" style="width: 300px" class="form-control" required maxlength="10" minLength="4"
[(ngModel)]="myPlanet.id"
ngControl="name"
#planetid="ngForm">
<div [hidden]="planetid.valid || planetid.pristine" class="alert alert-danger">
The id is required !
</div>
这里的"planetid.valid || planetid.pristine是验证这个input输入是否有效,或者数据是否改变。
Formbuilder
Formbuilder是我们可以采用的另一种方式来创建Form,这种方式是以模型驱动完成的,更适合我们进行编码控制,有利于我们将逻辑与视图分离。
Angular2 form 作用机制由两个主要的组件Controls和Controls group。
Control:包含值和验证状态,一个control能够被邦定可以包含三个可选参数(缺省值,验证,异步验证),例如
this.username = new Control('Default value', Validators.required, usernameValidator.checkIfAvailable);
在html应用时使用ngControl标签绑定这个控件
<input required type=”text” ngControl=”username” />
这里定义的username与input中ngControl指定的名称要一致。
Control Groups:form定义的一部分,通过将多个cotrol组合在一起形成组。
class App {
name: Control;
username: Control;
email: Control;
form: ControlGroup;
constructor(private builder:
FormBuilder) {
this.name = new Control('',
Validators.required);
this.email = new Control('',
Validators.required);
this.username = new Control('',
Validators.required);
this.form = builder.group({
name: this.name,
email: this.email,
username: this.username
});
}
};
html应用时加入ngFormModel来标识。
<form [ngFormModel]=”form”>
自定义验证
除了内置验证外,我们还可以自定义验证,例子如下
import {Control} from 'angular2/common';
interface ValidationResult
{
[key: string]: boolean;
}
export class UsernameValidator
{
static startsWithNumber( control: Control ): ValidationResult
{
if ( control.value !="" && !isNaN( control.value.charAt( 0 ) ) ){
return { "startsWithNumber": true };
}
return null;
}
}
这个自定义验证如果输入的值中首字母是数字则验证无效,返回null则验证通过。使用方法
首先import {UsernameValidator} from './customValidate';
然后在我们需要验证的控件上加入自定义验证
this.name = new Control( this.myPlanet.name, UsernameValidator.startsWithNumber );
错误提示
<div *ngIf="name.dirty && !name.valid">
<p *ngIf="name.errors.startsWithNumber">
Your name can't start with a number
</p>
</div>
这里的errors. startsWithNumber就是我们自定义返回的key值。最好的方式是使用hasError,因为如果返回的startsWithNumber是null的话会引发异常
<p *ngIf="name.hasError('startsWithNumber')">
异步验证
如果我们需要使用service去到后台获取数据并验证,则我们需要使用异步验证方式,这里的例子使用promise模拟。
static usernameTaken( control: Control ): Promise<ValidationResult>
{
let q = new Promise(( resolve, reject ) =>
{
setTimeout(() =>
{
if ( control.value !== 'oldkingsir') {
resolve( { "usernameTaken": true});
} else {
resolve( null );
}
}, 1000 )
});
return q;
}
真实应用可能是
class ProductValidator {
static productExists(control: Control): {[key: string]: any} {
return new Promise( resolve => {
var productService = new ProductService();
var product: Product;
productService.getProduct(control.value)
.then(productFound => {
if (productFound == null) {
// need to return something if not ok
resolve({productExists: false});
} else {
// need to return null if ok
resolve(null);
}
});
});
}
}
下面需要使用验证的第三个参数,方式如下
this.name = new Control( this.myPlanet.name,UsernameValidator.startsWithNumber, UsernameValidator.usernameTaken );
html
<div *ngIf="name.dirty && !name.valid">
<span *ngIf="name.pending">Checking istaken...</span>
<p *ngIf="name.hasError('startsWithNumber')">
Your name can't start with a number
</p>
<p *ngIf="name.hasError('usernameTaken')">
Your name is already taken
</p>
</div>
这里使用了pending来友好提示验证中。
组合验证
如果需要进行多个验证可以使用compose组合验证,如下
this.name = new Control('', Validators.compose([Validators.required, Validators.minLength(4)]));
最后如果整个表单验证不通过我们不提交则可以在提交按钮上加以处理,如
<button type="submit" class="btn btn-default" [disabled]="!form.valid">Submit</button>
angularjs2 学习笔记(六) Form的更多相关文章
- Angularjs2 学习笔记
angularjs2 学习笔记(一) 开发环境搭建 开发环境,vs2013 update 5,win7 x64,目前最新angular2版本为beta 17 第一步:安装node.js 安装nod ...
- java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)
java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...
- Learning ROS for Robotics Programming Second Edition学习笔记(六) indigo xtion pro live
中文译著已经出版,详情请参考:http://blog.csdn.net/ZhangRelay/article/category/6506865 Learning ROS for Robotics Pr ...
- Typescript 学习笔记六:接口
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- python3.4学习笔记(六) 常用快捷键使用技巧,持续更新
python3.4学习笔记(六) 常用快捷键使用技巧,持续更新 安装IDLE后鼠标右键点击*.py 文件,可以看到Edit with IDLE 选择这个可以直接打开编辑器.IDLE默认不能显示行号,使 ...
- Go语言学习笔记六: 循环语句
Go语言学习笔记六: 循环语句 今天学了一个格式化代码的命令:gofmt -w chapter6.go for循环 for循环有3种形式: for init; condition; increment ...
- 【opencv学习笔记六】图像的ROI区域选择与复制
图像的数据量还是比较大的,对整张图片进行处理会影响我们的处理效率,因此常常只对图像中我们需要的部分进行处理,也就是感兴趣区域ROI.今天我们来看一下如何设置图像的感兴趣区域ROI.以及对ROI区域图像 ...
- Linux学习笔记(六) 进程管理
1.进程基础 当输入一个命令时,shell 会同时启动一个进程,这种任务与进程分离的方式是 Linux 系统上重要的概念 每个执行的任务都称为进程,在每个进程启动时,系统都会给它指定一个唯一的 ID, ...
- # go微服务框架kratos学习笔记六(kratos 服务发现 discovery)
目录 go微服务框架kratos学习笔记六(kratos 服务发现 discovery) http api register 服务注册 fetch 获取实例 fetchs 批量获取实例 polls 批 ...
- Spring Boot 学习笔记(六) 整合 RESTful 参数传递
Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...
随机推荐
- HDU1272
http://acm.split.hdu.edu.cn/showproblem.php?pid=1272 对于这道题,只要找出形成的图是不是连通无环的图即可.即是判断输入的两个点是否来自同一个父亲结点 ...
- 初探接口测试框架--python系列6
点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...
- C/c++笔试经典程序(一)
1.输出结果比较 1) 输出结果:21 2) 输出结果:12.虽然循环只进行了一次,但是对!X++来说,X还是进行了自加运算. 2.指针运算 输出结果8,8.程序运行时,printf语句是从右往左进行 ...
- vss error reading from file 解决方法
vss error reading from file 解决方法 1 若服务器中存在 vss/data/backup目录,请将该目录删掉2 运行cmd cd.. cd C:\Program Files ...
- startup毕业论文
今天起得相对比较晚,为的是一个没有目的面试,去了的结果.只是打击一下自己的自信心,走的时候,面试官冷冷的说了一句,你的面试到此结束,是的,我并没有很伤心,在门外等面试的时候,我就非常的后悔,今天是不该 ...
- openstack openrpc
- php 几种函数类型
<?php header("Content-type:text/html;charset=utf-8"); $a=; $b=; function demo(){ global ...
- asp.net 在线人数
很网站都有在线人数,这一功能无处不在.现在,我们就介绍在.NET中一个简单明了的方法来统计在线用户的多少,该方法的特点就是充分的利用了ASP.NET的特点,结合global.asax文件,用Appli ...
- oracle11g ORA-12505
对于这个问题我前一天还可以用的,第二天打开就报这个错误了. 我在网上找了很多方法,大多为修改/listener.ora这个文件里的SID,修改后也没弄好. 我的解决方法很简单, 打开Oracle Ne ...
- 008sudo用户管理
1.Sudo是Unix/Linux平台上一个非常有用的工具,它允许系统管理员分配给普通用户一些合理的权利,让它们执行一些只有超级用户或其他特许用户才能完成的任务(主要体现为命令),比如,运行一些像mo ...