【发布时间】:2019-01-25 22:09:14
【问题描述】:
我得到一个对象数组作为响应,并将其分配给具有 formControlName 'custom' 的多选(ng-select)。我得到的响应是这样的
this.taskList = [
{ 'clientTaskId' : '1', 'taskName': 'hardware setup', billableRate: '500', customRate: ''},
{ 'clientTaskId' : '2', 'taskName': 'software installation', billableRate: '250', customRate: ''},
{ 'clientTaskId' : '3', 'taskName': 'environment setup', billableRate: '700', customRate: ''},
{ 'clientTaskId' : '4', 'taskName': 'cafeteria setup', billableRate: '1200', customRate: ''},
];
这是我的表单组
clientForm = this.fb.group([
custom: ['']
])
现在无论我选择什么对象。我将它填充到一个表格中,其中表格的一列是可编辑的。现在我在表格的可编辑列中编辑数据,当我点击保存按钮时,我应该得到编辑数据的响应。
我已使用 formControl 名称填充数据。
这是我的代码:
import {Component, NgModule, ViewChild} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormControl, FormGroup, ReactiveFormsModule, FormsModule, FormBuilder,Validators, FormArray} from '@angular/forms';
import {NgSelectModule, NgOption} from '@ng-select/ng-select';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="clientForm" (ngSubmit)="submit(clientForm.value)">
<ng-select
placeholder="Select custom rates"
[items]="taskList"
[multiple]="true"
bindLabel="taskName"
[addTag]="true"
[closeOnSelect]="false"
clearAllText="Clear"
formControlName = "custom"
>
</ng-select>
<br>
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col">Task Name</th>
<th scope="col">Custom Rate</th>
<th scope="col">Standard Rate</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let task of clientForm.controls['custom'].value">
<td>{{ task.taskName }}</td>
<td>
<input class="form-control form-control-sm" type="text" placeholder="" >
</td>
<td>{{ task.billableRate}}</td>
</tr>
</tbody>
</table>
<br>
<button type="submit">Submit</button>
</form>
<br>
`
})
export class AppComponent {
taskList : any;
ngOnInit() {
this.taskList = [
{ 'clientTaskId' : '1', 'taskName': 'hardware setup', billableRate: '500', customRate: ''},
{ 'clientTaskId' : '2', 'taskName': 'software installation', billableRate: '250', customRate: ''},
{ 'clientTaskId' : '3', 'taskName': 'environment setup', billableRate: '700', customRate: ''},
{ 'clientTaskId' : '4', 'taskName': 'cafeteria setup', billableRate: '1200', customRate: ''},
];
}
submit(formValue){
console.log(formValue)
}
clientForm = this.fb.group({
custom : ['']
})
constructor(private fb: FormBuilder ) { }
}
这里是演示: demo
我是 angular-reactive-forms 的初学者,我对如何使用 formArray 和 formGroup 有点困惑。以及如何处理对象数组的响应。
希望您理解我的问题,如果您需要任何澄清,请发表评论。
提前致谢。
【问题讨论】:
-
你想将响应作为数组修补吗??
-
我尝试将自定义分配为 formArray ,但它给出了不同的结果。我选择的选项应该作为表格中的双向绑定。但我不知道如何以反应形式做到这一点。正如我所提到的,我是响应式表单的新手,并且有点困惑如何处理这种情况
-
@Deepakparamesh 使用
array作为表单值,有更有效的方法,请说明您的需求,以便我们提供帮助。 -
@HamidAsghari 是的,我想将自定义作为数组。但是当我将它分配为 formArray 时,我无法填充自定义中已经存在的值。我引用了这些链接stackoverflow.com/questions/42968619/…ashish173.github.io/ng2-forms/trip/create。这与我的需求相似。
-
@Deepakparamesh
not able to populate the values already present in the custom是什么意思?
标签: angular angular-reactive-forms angular-ngselect