angular2 中的嵌套表单
[英] Nested Forms in angular2
本文介绍了angular2 中的嵌套表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建带有嵌套字段的表单,我知道 angular2 RC 中的 formArray
但有点困惑如何正确使用它?假设我有一个这样的表格
//主窗体,其中 formArray 命名为 `global_modifier`this.myForm = this._fb.group({......姓名: ['', []],global_modifier: this._fb.array([this.initGlobalModifiers()])....});removeModifier(i: number) {const control = <FormArray>this.myForm.controls['global_modifier'];control.removeAt(i);}addModifier() {const control = <FormArray>this.myForm.controls['global_modifier'];control.push(this.initGlobalModifiers());}/*global_modifier 函数具有名为 `items` 的嵌套字段 .....*/initGlobalModifiers() {返回 this._fb.group({.....modifier_title: ['', []],项目:this._fb.array([this.initItems()])…………});}删除项目(我:数字){const control = <FormArray>this.myForm.controls['items'];control.removeAt(i);}新增项目() {const control = <FormArray>this.myForm.controls['items'];control.push(this.initItems());}//项目初始化initItems() {返回 this._fb.group({item_title: ['', []],item_price: ['', []]});}
现在我很困惑如何在 html 中使用这个表单??
我正在尝试这个,但没有按预期工作..
<!--block For form mlutiple entrys---=------------><br>
</表单>
我的代码有什么错误?或者有人在 angular2 中有嵌套表单的工作示例吗?
解决方案
检查这个在 rc4 之前对我有用的例子(没有检查较新的版本):
表单标记
ngOnInit() {this.myForm = this.formBuilder.group({'loginCredentials': this.formBuilder.group({'登录': ['', Validators.required],'email': ['', [Validators.required, customValidator]],'密码':['',Validators.required]}),'爱好':this.formBuilder.array([this.formBuilder.group({'爱好': ['', Validators.required]})])});}删除爱好(索引:数字){(<FormArray>this.myForm.find('hobbies')).removeAt(index);}onAddHobby() {(<FormArray>this.myForm.find('hobbies')).push(new FormGroup({'爱好': new FormControl('', Validators.required)}))}
html 标记
注册页面
<form [formGroup]="myForm" (ngSubmit)="onSubmit()"><div formGroupName="loginCredentials"><div class="form-group"><div><label for="登录">登录</label><input id="login" type="text" class="form-control" formControlName="login"><div><label for="email">电子邮件</label><input id="email" type="text" class="form-control" formControlName="email">
<div><label for="password">密码</label><input id="password" type="text" class="form-control" formControlName="password">
<div class="row" ><div formGroupName="爱好"><div class="form-group"><label>爱好数组:</label><div *ngFor="let hobby of myForm.find('hobbies').controls; let i = index"><div formGroupName="{{i}}"><input id="hobby_{{i}}" type="text" class="form-control" formControlName="hobby"><button *ngIf="myForm.find('hobbies').length > 1" (click)="removeHobby(i)">x</button>
<button (click)="onAddHobby()">添加爱好</button>
<button type="submit" [disabled]="!myForm.valid">提交</button></表单>
备注
this.myForm = this.formBuilder.group
使用用户的配置创建一个表单对象并将其分配给 this.myForm 变量.
<小时>'loginCredentials': this.formBuilder.group
method 创建一组由 formControlName 组成的控件,例如.login
和 value ['', Validators.required],
其中第一个参数是表单输入的初始值,第二个参数是验证器或验证器数组,如在 'email': ['', [Validators.required, customValidator]],
.
<小时>'爱好':this.formBuilder.array
创建一个组的数组,其中组的索引是数组中的 formGroupName 并像这样访问:
<div formGroupName="{{i}}">...</div>
<小时>
onAddHobby() {(<FormArray>this.myForm.find('hobbies')).push(new FormGroup({'爱好': new FormControl('', Validators.required)}))}
这个示例方法将新的 formGroup 添加到数组中.当前访问需要指定我们想要访问的控件类型,在这个例子中这个类型是:
<小时>removeHobby(index: number){(<FormArray>this.myForm.find('hobbies')).removeAt(index);}
与上述相同的规则适用于从数组中删除特定的表单控件
How to create form with nesting fields, i know about formArray
in angular2 RC but am bit confused how to use it correctly ?
let suppose i have an form like this
// Main Form with formArray named as `global_modifier`
this.myForm = this._fb.group({
.......
name: ['', []],
global_modifier: this._fb.array([
this.initGlobalModifiers()
])
....
});
removeModifier(i: number) {
const control = <FormArray>this.myForm.controls['global_modifier'];
control.removeAt(i);
}
addModifier() {
const control = <FormArray>this.myForm.controls['global_modifier'];
control.push(this.initGlobalModifiers());
}
/*global_modifier function having nested fields named `items` .....*/
initGlobalModifiers() {
return this._fb.group({
.....
modifier_title: ['', []],
items: this._fb.array([
this.initItems()
])
.........
});
}
removeItem(i: number) {
const control = <FormArray>this.myForm.controls['items'];
control.removeAt(i);
}
addItem() {
const control = <FormArray>this.myForm.controls['items'];
control.push(this.initItems());
}
// items intilization
initItems() {
return this._fb.group({
item_title: ['', []],
item_price: ['', []]
});
}
now i am confused how to use this form in the html ??
i am trying this but did't work as expected..
<form [formGroup]="myForm" novalidate>
<input type="text" placeholder="name" formControlName="name" maxlength="50">
<div formArrayName="global_modifier" *ngFor="let cont of myForm.controls.global_modifier.controls; let i=index, let fst=first">
<div [formGroupName]="i">
<input type="text" placeholder="modifier_title" formControlName="modifier_title" maxlength="50">
<button *ngIf="fst" [ngClass]="{'inputAddButton ':fst}" (click)="addModifier(i)" type="button">
<i class="fa fa-plus fa-white" aria-hidden="true"></i>
</button>
<button *ngIf="!fst" [ngClass]="{'inputDeleteButton ':!fst}" (click)="removeModifier(i)">
<i class="fa fa-trash-o fa-white" aria-hidden="true"></i>
</button>
<!--block For form mlutiple entrys-------------------->
<div formArrayName="items">
<div *ngFor="let items of cont.items; let item_index=index, let fst=first">
<div [formGroupName]="i">
<div style="margin-bottom:10px">
............... NOTHING dISPLAY HERE ???
</div>
</div>
</div>
</div>
<!--block For form mlutiple entrys---=------------>
<br>
</div>
</div>
</form>
whats the error in my code ? or
anyone having working example of nested forms in angular2 ?
解决方案
Check this example that worked for me until rc4 (didn't check in newer versions):
form markup
ngOnInit() {
this.myForm = this.formBuilder.group({
'loginCredentials': this.formBuilder.group({
'login': ['', Validators.required],
'email': ['', [Validators.required, customValidator]],
'password': ['', Validators.required]
}),
'hobbies': this.formBuilder.array([
this.formBuilder.group({
'hobby': ['', Validators.required]
})
])
});
}
removeHobby(index: number){
(<FormArray>this.myForm.find('hobbies')).removeAt(index);
}
onAddHobby() {
(<FormArray>this.myForm.find('hobbies')).push(new FormGroup({
'hobby': new FormControl('', Validators.required)
}))
}
html markup
<h3>Register page</h3>
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div formGroupName="loginCredentials">
<div class="form-group">
<div>
<label for="login">Login</label>
<input id="login" type="text" class="form-control" formControlName="login">
</div>
<div>
<label for="email">Email</label>
<input id="email" type="text" class="form-control" formControlName="email">
</div>
<div>
<label for="password">Password</label>
<input id="password" type="text" class="form-control" formControlName="password">
</div>
</div>
</div>
<div class="row" >
<div formGroupName="hobbies">
<div class="form-group">
<label>Hobbies array:</label>
<div *ngFor="let hobby of myForm.find('hobbies').controls; let i = index">
<div formGroupName="{{i}}">
<input id="hobby_{{i}}" type="text" class="form-control" formControlName="hobby">
<button *ngIf="myForm.find('hobbies').length > 1" (click)="removeHobby(i)">x</button>
</div>
</div>
<button (click)="onAddHobby()">Add hobby</button>
</div>
</div>
</div>
<button type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
Remarks
this.myForm = this.formBuilder.group
creates a form object with user's configuration and assigns it to this.myForm variable.
'loginCredentials': this.formBuilder.group
method creates a group of controls which consist of a formControlName eg. login
and value ['', Validators.required],
where the first parameter is the initial value of the form input and the secons is a validator or an array of validators as in 'email': ['', [Validators.required, customValidator]],
.
'hobbies': this.formBuilder.array
Creates an array of groups where the index of the group is formGroupName in the array and is accessed like :
<div *ngFor="let hobby of myForm.find('hobbies').controls; let i = index">
<div formGroupName="{{i}}">...</div>
</div>
onAddHobby() {
(<FormArray>this.myForm.find('hobbies')).push(new FormGroup({
'hobby': new FormControl('', Validators.required)
}))
}
this sample method adds new formGroup to the array.
Currently accessing requires specifing the type of control we want to access, in this example this type is : <FormArray>
removeHobby(index: number){
(<FormArray>this.myForm.find('hobbies')).removeAt(index);
}
same rules as above apply to removing a specific form control from the array
这篇关于angular2 中的嵌套表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文