Angular2 表单:验证、ngControl、ngModel 等 [英] Angular2 Forms :Validations, ngControl, ngModel etc

查看:22
本文介绍了Angular2 表单:验证、ngControl、ngModel 等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

致力于 angular2 beta Forms.经过大量搜索发现没有任何用处.希望这里有人帮助我.

基本上我有点困惑如何以正确的方式在 angular2 中使用表单(即使用 ngControl、ngFormControl 等).我在这里创建了一个 plnkr

<块引用>

http://plnkr.co/edit/fictP28Vqn74YqrwM1jW?p=preview

这是我的 .html 代码:-

<div class="col-md-7">名称:<input type="text" id="name" placeholder="Name" class="form-control" ngControl="name">

<div class="col-md-7">密码:<input type="text" id="password" placeholder="password" class="form-control" ngControl="password">

<div class="col-md-7"><input type="radio" name='type'>Btech<input type="radio" name='type'>Mtech

<div class="col-md-7"><input type="checkbox" >数学<input type="checkbox">英文<input type="checkbox">科学

<br><div class="col-md-7"><select #selectOption (change)='getValue(selectOption.value)' class='form-control'><option value='1'>一个值</option><option value='2'>二值</option><option value='3'>三值</option></选择>

</表单><button type="button" (click)="addNewGroup(CreateGroup.value)" class="btn btn-primary btn-lg">创建</button>

和 .ts 代码在这里:-

CreateGroup: FormBuilder;构造函数(FB:FormBuilder){console.log('表单调用');this.CreateGroup = fb.group({'名称':新控件(),'密码':新的控制()})}添加新组(值){控制台日志(值);document.getElementById("myForm").reset();}获取值(值){控制台日志(值);}

我无法理解如何从完整的表单中获取作为对象的值.我的表单包括文本框、复选框、收音机和选择选项.下面是我的几个问题.

Q1:-如何在angular2中使用表单获取radio、checkbox、select的值.(我不想像我在 plnkr 中使用的那样为选择选项调用 change 钩子).

Q2:-如在plnkr提交数据后表单控件没有被重置.表单的控制仍然存在,但表单似乎已重置.那么如何在angular2中重置表单的控件.

Q3:- 在表单中使用验证的最佳方法是什么(如果有人有 plnkr 显示验证,请发布).

我已经阅读了这篇关于表单的文章,但仍然没有成功使用单选框和选择选项.

http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2

解决方案

将表单控件绑定到域模型

在组件中初始化域模型:

constructor(){this.student = 新学生();}

使用 ngModel 将表单控件绑定到具有双向模型绑定的域模型.

名称:密码:<input [(ngModel)]="student.password" type="text">

单击按钮时,将域模型作为参数传递:

实现 addNewGroup 方法.要重置表单,请使用新模型更新域模型:

addNewGroup(student:Student) {警报('添加' + 学生名);this.student = 新学生();}

演示 Plnkr

向表单添加验证器

要添加表单验证,请将 ngFormModel 添加到表单元素,并将 ngControl 装饰器添加到每个输入元素(ngControlngControl 的语法糖代码>[ngFormControl]="studentForm.controls['name']"):

<input type="text" ngControl="name"/><input type="text" ngControl="密码"/></表单>

ngFormModel 映射到组件的 ControlGroup 属性.使用属性名称对应于 ngControl 属性值的配置对象初始化 ControlGroup:

constructor(fb: FormBuilder){this.student = 新学生();this.studentForm = fb.group({'name': 新控件(this.student.name, Validators.required),'密码':新控件(this.student.password,Validators.required)});}

在上面的示例中,内置的required 验证器用于指示名称和密码是必填字段.然后,您可以使用表单模型上的 valid 属性检查整个表单是否有效:

addNewGroup(student:Student) {如果(this.studentForm.valid){警报('添加' + 学生名);this.student = 新学生();}别的 {alert('表单无效!');}}

演示 Plnkr

显示验证消息

如果您想绑定到视图中的验证消息,您可以将控件导出为本地模板变量并访问它的验证属性:有效、脏、未决、原始和错误对象.

 <span [hidden]="name.valid"><b>必需</b></span>

演示 Plnkr

如果您想创建自己的自定义验证器,请创建一个返回验证对象的方法,该对象的 boolean 属性对应于验证错误.例如,您可以创建一个验证器来确保密码的第一个字母必须是数字:

interface ValidationResult {[键:字符串]:布尔值;}类密码验证器{静态startsWithNumber(控制:控制):验证结果{if ( control.value && control.value.length > 0){如果 (isNaN(control.value[0]))返回 { 'startsWithNumber': true };}返回空;}}

将验证器组合成一个验证器,并使用内置的 Validators.compose 将其传递给 Control 构造函数:

this.studentForm = fb.group({'name': 新控件(this.student.name, Validators.required),'密码':新控件(this.student.password, Validators.compose([Validators.required,PasswordValidator.startsWithNumber])),});

如果你在同一个 Control 上有多个验证器,使用 errors 对象来区分它们:

<span [hidden]="!password.control.hasError('required')"><b>必需</b></span><span [hidden]="!password.control.hasError('startsWithNumber')"><b>必须以数字开头</b></span>

演示 Plnkr

绑定到单选按钮列表

在 Angular2 中,还没有绑定到单选按钮列表的内置支持.查看此帖子以了解如何执行此操作:

Angular2 - 单选按钮绑定

Working on angular2 beta Forms. after alot of searching found nothing useful. hope here somebody help me.

Basically i am bit confused how to use forms in angular2 in a proper manner (i.e using ngControl, ngFormControl etc). i have created one plnkr here

http://plnkr.co/edit/fictP28Vqn74YqrwM1jW?p=preview

here is my .html code:-

<form class="form-horizontal" id='myForm' role="form" [ngFormModel]="CreateGroup">

  <div class="col-md-7">
Name: <input type="text" id="name" placeholder="Name" class="form-control" ngControl="name">
  </div>
  <div class="col-md-7">
  Password:   <input type="text" id="password" placeholder="password" class="form-control" ngControl="password">
  </div>

  <div class="col-md-7">
    <input type="radio" name='type'>Btech
    <input type="radio" name='type'>Mtech
  </div>

  <div class="col-md-7">
    <input type="checkbox" >Math
    <input type="checkbox">English
    <input type="checkbox">Science
  </div>
  <br>
  <div class="col-md-7">
    <select #selectOption (change)='getValue(selectOption.value)' class='form-control'>
      <option value='1'>One Value</option>
      <option value='2'>two Value</option>
      <option value='3'>Three Value</option>
    </select>
  </div>
</form>
<button type="button" (click)="addNewGroup(CreateGroup.value)" class="btn btn-primary btn-lg"> Create </button>

and .ts code is here:-

CreateGroup: FormBuilder;
  constructor(fb: FormBuilder){
    console.log('form called');

    this.CreateGroup = fb.group({
            'name': new Control(),
            'password': new Control()
        })
  }
  addNewGroup(value) {
    console.log(value);
    document.getElementById("myForm").reset();
  }

  getValue(value){
    console.log(value);
  }

i am unable to understand how to get values as object from complete form. my form include textboxes,checkboxes,radio and select options. now here are few of my questions.

Q1:- How to get values of radio,checkbox,select using form in angular2. (i dont want to call change hook for select option as i have used in the plnkr).

Q2:- as in the plnkr after submitting data form control has not been reset. Control of the form remains present but form seems reset. so how to reset the control of forms in angular2.

Q3:- whats the best method to use validation in the forms (if anyone have plnkr showing validation please post it).

i had read this article on forms but still not succesfull with radio checkboxes and select options.

http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2

解决方案

Binding Form Controls to a Domain Model

Initialize the domain model within your component:

constructor(){
  this.student = new Student();
}

Use ngModel to bind to the form controls to a domain model with two-way model binding.

Name: <input [(ngModel)]="student.name" type="text">
Password:  <input [(ngModel)]="student.password" type="text">

When the button is clicked, pass the domain model as an argument:

<button type="button" (click)="addNewGroup(student)">Create</button>

Implement the addNewGroup method. To reset the form, update the domain model with a new model:

addNewGroup(student:Student) {
  alert('added ' + student.name);
  this.student = new Student();
}

Demo Plnkr

Adding Validators to the Form

To add form validation, add ngFormModel to the form element and add ngControl decorators to each input element (ngControl is syntactic sugar for [ngFormControl]="studentForm.controls['name']"):

<form [ngFormModel]="studentForm" />
   <input type="text" ngControl="name" />
   <input type="text" ngControl="password" />
</form>

The ngFormModel maps to a ControlGroup property of your component. Initialize the ControlGroup with a configuration object whose property names correspond to the values from the ngControl attributes:

constructor(fb: FormBuilder){
  this.student = new Student();
  this.studentForm = fb.group({
     'name': new Control(this.student.name, Validators.required),
     'password': new Control(this.student.password, Validators.required)
  });
}

In the above example, the built-in required validator is used to indicate that name and password are required fields. You can then check whether the entire form is valid using the valid property on the form model:

addNewGroup(student:Student) {
    if (this.studentForm.valid) {
      alert('added ' + student.name);
      this.student = new Student();
    }
    else {
      alert('form is not valid!');
    }
}

Demo Plnkr

Showing Validation Messages

If you want to bind to validation messages in the view, you can export the Control as a local template variable and access it's validation properties: valid, dirty, pending, pristine, and the errors object.

 <input ngControl="name" #name="ngForm" type="text">
 <span [hidden]="name.valid"><b>Required</b></span>

Demo Plnkr

If you want to create your own custom validator, create a method that returns a validation object whose boolean properties correspond to validation errors. For example, you can create a validator that ensures that the first letter of a password must be numeric:

interface ValidationResult {
 [key:string]:boolean;
}
class PasswordValidator {
 static startsWithNumber(control: Control): ValidationResult { 
   if ( control.value && control.value.length > 0){
     if (isNaN(control.value[0]))
      return { 'startsWithNumber': true };
   }

   return null;
 } 
}

Compose validators together into one validator and pass it to the Control constructor using the built-in Validators.compose:

this.studentForm = fb.group({
   'name': new Control(this.student.name, Validators.required),
   'password': new Control(this.student.password, Validators.compose([Validators.required,PasswordValidator.startsWithNumber])),
});

If you have multiple validators on the same Control, use the errors object to distinguish between them:

<input ngControl="password" #password="ngForm" />
<span [hidden]="!password.control.hasError('required')"><b>Required</b></span>
<span [hidden]="!password.control.hasError('startsWithNumber')"><b>Must start with number</b></span>

Demo Plnkr

Binding to Radio Button Lists

In Angular2, there is no built-in support yet to bind to radio button lists. Check this post to find out how to do this:

Angular2 - Radio Button Binding

这篇关于Angular2 表单:验证、ngControl、ngModel 等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆