我有表格阵列,我很难解决这个问题.
这是我目前的代码
.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>
我很难如何填充和推动.我找不到任何教程.
编辑
提交时我想要这样的东西
{ codeId: 123,name: "wew",stepTextarea: "",steps: ['asdjlkas','12312','12321'] }
由于您希望步骤在提交时显示如下:
steps: ['asdjlkas','12321']
你不应该在步骤中使用formGroup.
表单的构建应如下所示:
ngOnInit() { this.item = this.fb.group({ codeId: ['',stepTextarea: [''],steps: this.fb.array([]) // do not enclose steps inside an array }); }
编辑:
这将是你的addProcedure的样子:
addStep() { const control = <FormArray>this.item.controls['steps']; // push the value from stepTextArea to array control.push(new FormControl(this.item.get('stepTextArea').value)) // reset this.item.get('stepTextArea').reset() }
你的模板看起来像这样:
<div formArrayName="steps"> <h3>Steps: </h3> <ol *ngFor="let step of item.controls.steps.controls; let i = index"> <span>{{step.value}}</span> </ol> </div>
原始答案解决方法如何做FormArray:
addProcedure应如下所示:
addProcedure (e): void { const steps = <FormArray>this.item.controls['steps']; steps.push(new FormControl()) }
你的formarray模板应该是这样的:
<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>