angular2 中的表单 [英] Forms In angular2

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

问题描述

对如何在 angular2 beta 中使用表单(模板或模态驱动)感到困惑.

目前我正在使用模态驱动的表单,但在我的 form.html 中出现一些错误:

<input type="text" [ngFormControl]="demo.controls['name']"><input type="text" [ngFormControl]="demo.controls['batch']"><div><input type="radio" [ngFormControl]="demo.controls['radio']" name="status" value="true">积极的<input type="radio" [ngFormControl]="demo.controls['radio']" name="status" value="false">Inactive

<div><input type="checkbox" [ngFormControl]="demo.controls['checkbox']" name="one" value="one">一<input type="checkbox" [ngFormControl]="demo.controls['checkbox']" name="two" value="two">two

<select [ngFormControl]="demo.controls['select']"><option value="one">Oone</option><option value="two">two</option><option value="三">三</option><option value="four">four</option></选择><button type="button" class="btn btn-primary btn-lg" data-dismiss="modal" (click)="demoSubmit(demo.value)">完成</button></表单>

和 form.ts 文件在这里:

import {Component, View} from 'angular2/core';从'angular2/common'导入{FORM_DIRECTIVES、CORE_DIRECTIVES、FormBuilder、Control、ControlGroup};从'angular2/router'导入{ROUTER_DIRECTIVES};@成分({选择器:'表格',templateUrl: 'src/components/form/form.html',指令:[CORE_DIRECTIVES,FORM_DIRECTIVES],})导出类 FormDemo{演示:控制组;构造函数(FB:FormBuilder){console.log("表单调用");this.demo= fb.group({名称:[pardeep"],批: [],复选框:[],收音机: [],选择: []})}演示提交(){console.log(JSON.stringify(this.demo.value));}}

所以,我的问题是:

  1. 哪种表单是最好的模板或模态驱动,为什么?
  2. 何时使用 ngControl 以及何时使用 ngModal ?

PS:- 在这个例子中,我无法获得单选按钮和复选框的值是我做错了什么,在这个例子中我是来自 这里?

欢迎任何好的参考或示例.谢谢.

解决方案

在 angular2 中清除了一些与 FORMs 相关的要点,因此作为答案发布可能对某人有所帮助!

什么时候用 ngControl 什么时候用 ngModel ?

基本上我们可以使用 ngControl 来获取表单的值和验证,但是有一些使用这种方法的问题,所以最好的解决方案是根据我的说法使用 ngModel 来获取表单的值您的类并使用 ngControl 进行验证.angular 提供了默认验证器来检查验证,我们也可以根据需要创建自定义验证器,并可以在验证中使用 (ngControl).如果我们要创建模型驱动的表单,即我们必须使用 new Control() 为每个输入创建新控件.对照组、对照组和验证参考这篇最佳文章

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

这里是使用表单控件的基本示例:

this.CreateGroup = fb.group({'name': 新控件(this.demoInfo.name, Validators.required),'密码':新控件(this.demoInfo.password,Validators.required),'选择':新控件(this.demoInfo.select,Validators.required)})

这里我有三个输入分别命名为名称、密码、选择.和相应的我已经提到了它们的值和验证器(默认验证).

这里是我们如何定义 ngControl 到 HTML 端.

带有控件和验证的 Angular2 表单.

经过大量搜索,我得出结论,使用 ngModel 最好从表单中获取值.通过使用它,更容易清除表单的控件.并且验证变得容易.并使用 ngControl 来检查验证.

这是我的表单工作代码.

<div class="col-md-7">名称:<输入类型=文本"[(ngModel)]='demoInfo.name' class="form-control";ngControl='名称'>

<div class="col-md-7">密码:<输入类型=密码";[(ngModel)]='demoInfo.password' class="form-control";ngControl='密码'>

<div class="col-md-7"><输入类型=收音机"name='type'(点击)='demoInfo.radio="Btech"'[checked]="'Btech' === demoInfo.radio">Btech<输入类型=收音机"name='type'(点击)='demoInfo.radio="Mtech"'[checked]="'Mtech' === demoInfo.radio">Mtech

<div class="col-md-7"><select #selectOption (change)='demoInfo.select=selectOption.value' class='form-control' ngControl='select'><选项>选择<option value='One' [selected]="demoInfo.select==='One'">One Value</option><option value='Two' [selected]="demoInfo.select==='Two'">two Value</option><option value='Three' [selected]="demoInfo.select==='Three'">三值</option></选择>

</表单><br>

<按钮类型=按钮"[禁用]='!CreateGroup.valid'(点击)=addNewGroup(demoInfo)";class=btn btn-primary">创建</button>

类方面的代码在这里...

import {Component} from 'angular2/core';从'angular2/common'导入{CORE_DIRECTIVES, NgClass, FORM_DIRECTIVES, Control, ControlGroup, FormBuilder, Validators};类演示信息{名称:字符串;密码:字符串;无线电:任何;选择:任何;}@成分({选择器:'我的应用',templateUrl: 'mytemplate.html',指令:[CORE_DIRECTIVES, FORM_DIRECTIVES]})导出类 AppComponent {创建组:FormBuilder;演示信息:演示信息;构造函数(FB:FormBuilder){this.demoInfo=新的DemoInfo();this.CreateGroup = fb.group({'name': 新控件(this.demoInfo.name, Validators.required),'密码':新控件(this.demoInfo.password,Validators.required),'选择':新控件(this.demoInfo.select,Validators.required)})}addNewGroup(demoInfo:demoInfo) {console.log(demoInfo, '整个对象');this.demoInfo=新的DemoInfo();}}

参考这里工作 plunkr 在这里.

Bit confused about how to use Forms(template or modal driven froms) in the angular2 beta.

currently i am using modal driven forms but getting some error here is my form.html:

<form [ngFormModel]="demo">
        <input type="text"  [ngFormControl]="demo.controls['name']">
        <input type="text"  [ngFormControl]="demo.controls['batch']">
        <div> 
            <input type="radio" [ngFormControl]="demo.controls['radio']" name="status" value="true"> Active
            <input type="radio" [ngFormControl]="demo.controls['radio']" name="status" value="false">Inactive 
        </div>
        <div> 
            <input type="checkbox" [ngFormControl]="demo.controls['checkbox']" name="one" value="one"> one
            <input type="checkbox" [ngFormControl]="demo.controls['checkbox']" name="two" value="two">two 
        </div>
        <select [ngFormControl]="demo.controls['select']">
            <option value="one">Oone</option>
            <option value="two">two</option>
            <option value="three">three</option>
            <option value="four">four</option>
        </select>
        <button type="button" class="btn btn-primary btn-lg" data-dismiss="modal" (click)="demoSubmit(demo.value)">Done</button>
</form>

and form.ts file is here:

import {Component, View} from 'angular2/core';
import {FORM_DIRECTIVES, CORE_DIRECTIVES, FormBuilder, Control, ControlGroup} from 'angular2/common';
import {ROUTER_DIRECTIVES} from 'angular2/router';

@Component({
    selectro: 'Form',
    templateUrl: 'src/components/form/form.html',
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES],
})
export class FormDemo{
    demo:ControlGroup;
    constructor(fb:FormBuilder){
        console.log("Form Called");

        this.demo= fb.group({
            name: ["pardeep"],
            batch: [],
            checkbox: [],
            radio: [],
            select: []
        })
    }
    demoSubmit (){
        console.log(JSON.stringify(this.demo.value));
    }
}

so, my questions is:

  1. which form is best template or modal driven and why ?
  2. when to use ngControl and when to use ngModal ?

PS:- in this example i am unable to get the values of radio button and check-box selected am i doing something wrong, in this example i am modal driven form From here?

any good reference or example is welcome. thanks.

解决方案

Got cleared some points related to FORMs in angular2 so posting as answer may help to someone !!

when to use ngControl and when to use ngModel ?

Basically we can ngControl for both to get values of forms as well as for validations but there are some probelms using this methods so best solution is according to me use ngModel for getting values of the form into your class and use ngControl for the validation purpose. there are default validators provide by angular to check validation we can create our custom one too as per need and can use in the validation (ngControl). if we are going to create model driven form i.e we have to create new control for every input by using new Control(). for the Control, control group and validation refer this best artical

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

here is the basic example of using controls for the form:

this.CreateGroup = fb.group({
            'name': new Control(this.demoInfo.name, Validators.required),
            'password': new Control(this.demoInfo.password, Validators.required),
            'select': new Control(this.demoInfo.select, Validators.required)
        })

Here i have three inputs named name, password,select respectively. and corresponding i have mentioned their values and validators (default validation).

<input type="text" [(ngModel)]='demoInfo.name' ngControl='name'>

here is how we define ngControl to out HTML side.

Angular2 FORM with controls and validation.

After a lot searching i concluded that using ngModel is best to get values from form. by using same it is easier to clear to controls of the forms. and validations gets easy. and used ngControl for checking validations.

here is my working code for the form.

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

  <div class="col-md-7">
    Name: <input type="text" [(ngModel)]='demoInfo.name' class="form-control" ngControl='name'>
  </div>
  
  <div class="col-md-7">
    Password:   <input type="password" [(ngModel)]='demoInfo.password' class="form-control" ngControl='password'>
  </div>
   
  <div class="col-md-7">
    <input type="radio" name='type' (click)='demoInfo.radio="Btech"' [checked]="'Btech' === demoInfo.radio">Btech
    <input type="radio" name='type' (click)='demoInfo.radio="Mtech"' [checked]="'Mtech' === demoInfo.radio">Mtech
  </div>
  
  <div class="col-md-7">
    <select #selectOption (change)='demoInfo.select=selectOption.value' class='form-control' ngControl='select'>
      <option> select</option>
      <option value='One' [selected]="demoInfo.select==='One'">One Value</option>
      <option value='Two' [selected]="demoInfo.select==='Two'">two Value</option>
      <option value='Three' [selected]="demoInfo.select==='Three'">Three Value</option>
    </select>
  </div>
</form>
<br>
<div class='text-center'>
  <button type="button" [disabled]='!CreateGroup.valid' (click)="addNewGroup(demoInfo)" class="btn btn-primary">Create</button>
</div>

and code for the class side is here...

import {Component} from 'angular2/core';
import {CORE_DIRECTIVES, NgClass, FORM_DIRECTIVES, Control, ControlGroup, FormBuilder, Validators} from 'angular2/common';

class DemoInfo{
  name:string;
  password: string;
  radio: any;
  select: any;
}
@Component({
    selector: 'my-app',
    templateUrl: 'mytemplate.html',
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES] 
})
export class AppComponent { 
  CreateGroup: FormBuilder;
  demoInfo: DemoInfo;
  constructor(fb: FormBuilder){
    this.demoInfo= new DemoInfo(); 
    
    this.CreateGroup = fb.group({
            'name': new Control(this.demoInfo.name, Validators.required),
            'password': new Control(this.demoInfo.password, Validators.required),
            'select': new Control(this.demoInfo.select, Validators.required)
        })
  }
  addNewGroup(demoInfo:demoInfo) {
    console.log(demoInfo, 'whole object');
    this.demoInfo= new DemoInfo();
  }
}

refer this for working plunkr here .

这篇关于angular2 中的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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