本文介绍了如何在不使用Angular 2的FormBuilder的情况下推送FormArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有表格数组,我很难解决这个问题.
I have form array, I am having hard time solving this.
这是我当前的代码
.ts
ngOnInit() {
this.item = this.fb.group({
codeId: ['', Validators.pattern(/^\d+$/)],
name: ['', [Validators.required, Validators.minLength(3)]],
stepTextarea: ['', []],
steps: [this.fb.array([]), []]
});
}
addProcedure (e): void {
e.preventDefault();
const control = <FormGroup>this.item;
const steps = <FormArray>this.item.controls['steps'];
steps.push(control.get('stepTextarea').value);
control.get('stepTextarea').setValue("", {onlySelf: true})
}
onSubmit({value, valid}: {value: Item, valid: boolean}): void {
const control = <FormGroup>this.item;
console.log(value);
}
.html
<ol ngFor [ngForOf]="item.get('steps').controls">
<span [formGroupName]="i">{{i}}</span>
</ol>
我很难填充和推送.我找不到任何教程.
I am having hard time how to populate and also push. I cant find any tutorial.
编辑
我想要这样的东西
{
codeId: 123,
name: "wew",
stepTextarea: "",
steps: ['asdjlkas','12312','12321']
}
推荐答案
由于您希望提交时的步骤如下所示:
Since you want the steps to look like this on submit:
steps: ['asdjlkas','12312','12321']
您不应该在步骤内使用formGroup.
you shouldn't use formGroup inside steps.
表单的构建应如下所示:
The build of the form should look like this:
ngOnInit() {
this.item = this.fb.group({
codeId: ['', Validators.pattern(/^\d+$/)],
name: ['', [Validators.required, Validators.minLength(3)]],
stepTextarea: [''],
steps: this.fb.array([]) // do not enclose steps inside an array
});
}
这就是您的addProcedure
的样子:
addStep() {
const control = <FormArray>this.item.get('steps');
// push the value from stepTextArea to array
control.push(this.fb.control(this.item.get('stepTextArea').value))
// reset
this.item.get('stepTextArea').reset()
}
您的模板如下所示:
<div formArrayName="steps">
<h3>Steps: </h3>
<ol *ngFor="let step of item.get('steps').controls; index as i">
<span>{{step.value}}</span>
</ol>
有关如何执行FormArray的解决方案的原始答案:
Original answer with solution of how to do FormArray:
addProcedure
应该看起来像这样:
addProcedure (e): void {
const steps = <FormArray>this.item.get('steps');
steps.push(this.fb.control())
}
您的formarray模板应如下所示:
And your template for formarray should look something like this:
<div formArrayName="steps">
<div *ngFor="let step of item.controls.steps.controls; let i = index" >
<label>Step {{i+1}} </label>
<input [formControlName]="i" />
</div>
</div>
这篇关于如何在不使用Angular 2的FormBuilder的情况下推送FormArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!