angular2中的表格
Forms In angular2
对如何在 angular2 beta 中使用表单(模板或模态驱动)感到困惑。
目前我正在使用模态驱动表单,但我的 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>
和 form.ts 文件在这里:
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));
}
}
所以,我的问题是:
- 哪种形式是最好的模板或模态驱动,为什么?
- 何时使用 ngControl 以及何时使用 ngModal?
PS:- 在这个例子中,我无法获取单选按钮和复选框的值,我做错了什么,在这个例子中,我是模态驱动形式来自 here ?
欢迎任何好的参考或示例。
谢谢。
我的选择是使用ngFormModel
和ngControl
,因为我们可以更容易地收集表单数据并可以进行验证等
有关详细信息,请参阅我的 angular2-seeds 项目
我猜你所说的 ngModal 是指 ngModel。
“1-哪种形式是最好的模板或模态驱动,为什么?”
来自:http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/
要创建新的 ControlGroup 和控件,请隐式使用:
ngForm
和 ngControl
要绑定到现有的 ControlGroup 和控件,请使用:
ngFormModel
和 ngFormControl
基本上一个更方便,但给你更少的控制,我个人首先尝试使用模板驱动,因为它更简单,代码更少,直到它不够用,然后我切换到模型驱动。
2- 什么时候使用 ngControl 什么时候使用 ngModel ?
我不知道你是否在这里混淆了概念,但 ngControl 和 ngModel 并不完全意味着要相互替换,ngModel 处理输入组件和你的 domain/presentation 模型之间的同步,而 ngControl 处理基于验证器的表单、输入的脏度等,更适合提供反馈和 allowing/stopping 用户提交无效表单。
可以相互替代的就是我之前在回答1中提到的
我希望这有助于澄清一点?
至于复选框和收音机的值,您只有 ngFormControl 的,添加 ngModel 以将它们的值映射到您的模型中。再次引用同一页:
<input type="text" id="productNameInput" placeholder="Product Name" [ngFormControl]="myForm.find('productName')" [(ngModel)]="productName">
你可以看到他同时使用了ngFormControl
和ngModel
。
尝试在您的表单生成器中使用 new RadioButtonState(boolean, string)
。
例如
模板:
<form [ngFormModel]="form" (ngSubmit)="doIt()">
<h3>DisOrDat</h3>
<hr />
<p>Choose</p>
<div ngControlGroup="disOrDat">
<div class="radio">
<label>
<input type="radio" name="choose" value="dis" ngControl="dis">Dis
</label>
<label>
<input type="radio" name="choose" value="dat" ngControl="dat">Dat
</label>
</div>
</div>
</form>
组件
// create the form as a colleciton of Controls
this.form = formBuilder.group({
disOrDat: formBuilder.group(
{
dis: [new RadioButtonState(true, 'dis')],
dat: [new RadioButtonState(false, 'dat')]
},
{
validator: this.disOrDatValidator
}
)
});
disOrDatValidator(group: ControlGroup) {
/* tslint:disable:no-string-literal */
if (group.controls['dis'].value !== group.controls['dat'].value) {
/* tsslint:enable:no-string-literal */
return false;
}
// return null means validation passed
return null;
}
doIt() {
// handle form submit
}
在 angular2 中清除了一些与表格相关的要点,因此作为答案发布可能对某人有帮助!!
何时使用 ngControl 以及何时使用 ngModel ?
基本上我们可以 ngControl 来获取表单的值和验证,但是有一些问题使用这种方法所以最好的解决方案是根据我使用 ngModel
来获取表单的值到你的class 并使用 ngControl
进行验证。 angular 提供了默认验证器来检查验证,我们也可以根据需要创建自定义验证器,并可以在验证中使用 (ngControl)。如果我们要创建模型驱动的表单,即我们必须使用 new Control()
为每个输入创建新控件。
对于控制、控制组和验证,请参考这篇最佳文章
http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/
下面是使用表单控件的基本示例:
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)
})
这里我有三个输入名称,密码,select。相应的我已经提到了它们的值和验证器(默认验证)。
<input type="text" [(ngModel)]='demoInfo.name' ngControl='name'>
这里是我们如何将 ngControl 定义到 HTML 端。
带有控件和验证的 Angular2 FORM。
经过大量搜索后,我得出结论,使用 ngModel 是从表单获取值的最佳选择。通过使用相同的,更容易清除表单的控件。并且验证变得容易。并使用 ngControl
来检查验证。
这是我的表单工作代码。
<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>
class 端的代码在这里...
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();
}
}
在这里参考这个工作 plunkr
.
已更新 - Angular2 RC4 格式
(新表格有很多变化,所以作为新答案发布)
angular2 RC Forms 发布后,angular2 forms 发生了很多变化。其中一些是重大的突破性变化,其中一些可以忽略不计,这里是使用 angular2 表单的一些关键点。
Angular2中基本上有两种构建表单的方法,即模板驱动和模型驱动。
使用表单的基本结构如下:-
- 运行
npm install @angular/forms --save
为您的应用配置 bootstrap 方法如下:
bootstrap(AppComponent, [
disableDeprecatedForms(), // disable deprecated forms
provideForms(), // enable new forms module
]);
使用 REACTIVE_FORM_DIRECTIVES
组件指令以使用表单功能。
- 创建
FormGroup
类型的表单变量
- 使用
Validators
进行验证。
除此之外
FormBuilder 不是构建模型驱动表单的强制性工具,但它简化了语法。 formbuilder 提供的三个基本 syntax/method 是:
- 组:构造一个新的表单组。
- array: 构造一个新的表格数组。
- control: 构造一个新的表单控件
这些是在 angular2 RC 中使用表单的基本步骤。
angular2 表单的有用资源:
https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol
https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2
在此处进行相同的现场演示
对如何在 angular2 beta 中使用表单(模板或模态驱动)感到困惑。
目前我正在使用模态驱动表单,但我的 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>
和 form.ts 文件在这里:
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));
}
}
所以,我的问题是:
- 哪种形式是最好的模板或模态驱动,为什么?
- 何时使用 ngControl 以及何时使用 ngModal?
PS:- 在这个例子中,我无法获取单选按钮和复选框的值,我做错了什么,在这个例子中,我是模态驱动形式来自 here ?
欢迎任何好的参考或示例。 谢谢。
我的选择是使用ngFormModel
和ngControl
,因为我们可以更容易地收集表单数据并可以进行验证等
有关详细信息,请参阅我的 angular2-seeds 项目
我猜你所说的 ngModal 是指 ngModel。
“1-哪种形式是最好的模板或模态驱动,为什么?”
来自:http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/
要创建新的 ControlGroup 和控件,请隐式使用:
ngForm
和 ngControl
要绑定到现有的 ControlGroup 和控件,请使用:
ngFormModel
和 ngFormControl
基本上一个更方便,但给你更少的控制,我个人首先尝试使用模板驱动,因为它更简单,代码更少,直到它不够用,然后我切换到模型驱动。
2- 什么时候使用 ngControl 什么时候使用 ngModel ?
我不知道你是否在这里混淆了概念,但 ngControl 和 ngModel 并不完全意味着要相互替换,ngModel 处理输入组件和你的 domain/presentation 模型之间的同步,而 ngControl 处理基于验证器的表单、输入的脏度等,更适合提供反馈和 allowing/stopping 用户提交无效表单。
可以相互替代的就是我之前在回答1中提到的
我希望这有助于澄清一点?
至于复选框和收音机的值,您只有 ngFormControl 的,添加 ngModel 以将它们的值映射到您的模型中。再次引用同一页:
<input type="text" id="productNameInput" placeholder="Product Name" [ngFormControl]="myForm.find('productName')" [(ngModel)]="productName">
你可以看到他同时使用了ngFormControl
和ngModel
。
尝试在您的表单生成器中使用 new RadioButtonState(boolean, string)
。
例如
模板:
<form [ngFormModel]="form" (ngSubmit)="doIt()">
<h3>DisOrDat</h3>
<hr />
<p>Choose</p>
<div ngControlGroup="disOrDat">
<div class="radio">
<label>
<input type="radio" name="choose" value="dis" ngControl="dis">Dis
</label>
<label>
<input type="radio" name="choose" value="dat" ngControl="dat">Dat
</label>
</div>
</div>
</form>
组件
// create the form as a colleciton of Controls
this.form = formBuilder.group({
disOrDat: formBuilder.group(
{
dis: [new RadioButtonState(true, 'dis')],
dat: [new RadioButtonState(false, 'dat')]
},
{
validator: this.disOrDatValidator
}
)
});
disOrDatValidator(group: ControlGroup) {
/* tslint:disable:no-string-literal */
if (group.controls['dis'].value !== group.controls['dat'].value) {
/* tsslint:enable:no-string-literal */
return false;
}
// return null means validation passed
return null;
}
doIt() {
// handle form submit
}
在 angular2 中清除了一些与表格相关的要点,因此作为答案发布可能对某人有帮助!!
何时使用 ngControl 以及何时使用 ngModel ?
基本上我们可以 ngControl 来获取表单的值和验证,但是有一些问题使用这种方法所以最好的解决方案是根据我使用 ngModel
来获取表单的值到你的class 并使用 ngControl
进行验证。 angular 提供了默认验证器来检查验证,我们也可以根据需要创建自定义验证器,并可以在验证中使用 (ngControl)。如果我们要创建模型驱动的表单,即我们必须使用 new Control()
为每个输入创建新控件。
对于控制、控制组和验证,请参考这篇最佳文章
http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/
下面是使用表单控件的基本示例:
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)
})
这里我有三个输入名称,密码,select。相应的我已经提到了它们的值和验证器(默认验证)。
<input type="text" [(ngModel)]='demoInfo.name' ngControl='name'>
这里是我们如何将 ngControl 定义到 HTML 端。
带有控件和验证的 Angular2 FORM。
经过大量搜索后,我得出结论,使用 ngModel 是从表单获取值的最佳选择。通过使用相同的,更容易清除表单的控件。并且验证变得容易。并使用 ngControl
来检查验证。
这是我的表单工作代码。
<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>
class 端的代码在这里...
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();
}
}
在这里参考这个工作 plunkr .
已更新 - Angular2 RC4 格式
(新表格有很多变化,所以作为新答案发布)
angular2 RC Forms 发布后,angular2 forms 发生了很多变化。其中一些是重大的突破性变化,其中一些可以忽略不计,这里是使用 angular2 表单的一些关键点。
Angular2中基本上有两种构建表单的方法,即模板驱动和模型驱动。 使用表单的基本结构如下:-
- 运行
npm install @angular/forms --save
为您的应用配置 bootstrap 方法如下:
bootstrap(AppComponent, [ disableDeprecatedForms(), // disable deprecated forms provideForms(), // enable new forms module ]);
使用
REACTIVE_FORM_DIRECTIVES
组件指令以使用表单功能。- 创建
FormGroup
类型的表单变量
- 使用
Validators
进行验证。
除此之外 FormBuilder 不是构建模型驱动表单的强制性工具,但它简化了语法。 formbuilder 提供的三个基本 syntax/method 是:
- 组:构造一个新的表单组。
- array: 构造一个新的表格数组。
- control: 构造一个新的表单控件
这些是在 angular2 RC 中使用表单的基本步骤。
angular2 表单的有用资源:
https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol
https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2
在此处进行相同的现场演示