简体   繁体   English

Angular2形式:验证,ngControl,ngModel等

[英]Angular2 Forms :Validations, ngControl, ngModel etc

Working on angular2 beta Forms . 在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 (ie using ngControl, ngFormControl etc). 基本上,我有点困惑如何以适当的方式(例如,使用ngControl,ngFormControl等)在angular2中使用表格。 i have created one plnkr here 我在这里创建了一个plnkr

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

here is my .html code:- 这是我的.html代码:-

<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:- .ts代码在这里:

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. Q1:-如何获取radio的值,复选框,使用angular2中的表格进行选择。 (i dont want to call change hook for select option as i have used in the plnkr). (我不想像我在plnkr中使用的那样为选择选项调用change钩子)。

Q2:- as in the plnkr after submitting data form control has not been reset. 问题2:-如提交数据表单控件后未重置plnkr。 Control of the form remains present but form seems reset. 窗体的控件仍然存在,但窗体似乎已重置。 so how to reset the control of forms in angular2. 因此,如何在angular2中重置表格的控件。

Q3:- whats the best method to use validation in the forms (if anyone have plnkr showing validation please post it). 问题3:-在表单中使用验证的最佳方法是什么(如果有人显示plnkr验证,请发布它)。

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 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. 使用ngModel通过双向模型绑定将表单控件绑定到域模型。

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. 实现addNewGroup方法。 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']" ): 要添加表单验证, ngFormModel在表单元素中添加ngControl并在每个输入元素中添加ngControl装饰器( ngControl[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. ngFormModel映射到组件的ControlGroup属性。 Initialize the ControlGroup with a configuration object whose property names correspond to the values from the ngControl attributes: 使用配置对象初始化ControlGroup ,该配置对象的属性名称与ngControl属性中的值相对应:

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. 在上面的示例中,内置的required验证器用于指示名称和密码为必填字段。 You can then check whether the entire form is valid using the valid property on the form model: 然后,您可以使用表单模型上的valid属性来检查整个表单是否有效:

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. 如果要绑定到视图中的验证消息,则可以将Control导出为本地模板变量,并访问其验证属性:有效,脏,挂起,原始和错误对象。

 <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. 如果要创建自己的自定义验证器,请创建一个返回验证对象的方法,该对象的boolean属性与验证错误相对应。 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 : 将验证器组合到一个验证器中,然后使用内置的Validators.compose将其传递给Control构造函数:

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: 如果在同一Control上有多个验证器,请使用errors对象来区分它们:

<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. 在Angular2中,尚不存在绑定到单选按钮列表的内置支持。 Check this post to find out how to do this: 检查此帖子以了解如何执行此操作:

Angular2 - Radio Button Binding Angular2-单选按钮绑定

UPADTED - ANGULAR2 RC4 FORMS 已更新-ANGULAR2 RC4格式

TL;DR; TL; DR;

After the release of angular2 RC Forms there are lot of changes have been made in angular2 forms. 在发布angular2 RC形式后,对angular2形式进行了很多更改。 there are some of them are major breaking changes some of them are negligible, here are some key points for using angular2 forms. 其中有些是重大突破,有些可以忽略,这是使用angular2形式的一些要点。

Basically there are two ways to build forms in Angular 2, namely template-driven and model-driven. 基本上,有两种方法可以在Angular 2中构建表单,即模板驱动和模型驱动。 basic structure for using forms are as follows:- 使用表格的基本结构如下:

  • run npm install @angular/forms --save 运行npm install @angular/forms --save
  • configure bootstrap method for your app as following: 为您的应用配置引导方法,如下所示:

     bootstrap(AppComponent, [ disableDeprecatedForms(), // disable deprecated forms provideForms(), // enable new forms module ]); 
  • use REACTIVE_FORM_DIRECTIVES to component directives to use forms functionality. 使用REACTIVE_FORM_DIRECTIVES到组件指令以使用表单功能。

  • create Form variable of type FormGroup 创建FormGroup类型的Form变量
  • Use Validators for validatiion purpose. 使用Validators进行验证。

apart from this FormBuilder is not a mandatory to building model driven form, but it simplify the syntax. 除了此FormBuilder之外,构建模型驱动的表单不是必需的,但是它简化了语法。 there are three basic syntax/method provided by formbuilder are: formbuilder提供了三种基本语法/方法:

  • group : construct a new form group. :构造一个新的表单组。
  • array : construct a new form array. array :构造一个新的表单数组。
  • control : construct a new form control. 控件 :构造一个新的窗体控件。

These are the basic steps to use forms in angular2 RC. 这些是在angular2 RC中使用表格的基本步骤。

Usefull resources for angular2 forms: angular2形式的有用资源:

Live Demo for the same here 现场演示同样在这里

Working Demo for angular2 Forms angular2表单的工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM