我正在将对象响应数组加载到多选(ng-select)中。我的回应是这样
formModel就是这样
clientForm = this.fb.group({
custom : this.fb.array([this.fb.group({
clientTaskId: [''],
taskName: [''],
billableRate: [''],
customRate: ['']
})]),
})
在多选中选择选项时,无法在formArrayName'custom'中获取值。但是,当我使用“ custom”作为“ formControlName”时,我能够获得所选择的对象。
这是我的代码:
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"
formArrayName = "custom"
>
</ng-select>
<br>
<pre>{{clientForm.value | json}}</pre>
<br>
<button type="submit">Submit</button>
</form>
<br>
`
})
export class AppComponent {
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: ''},
];
ngOnInit() {
this.taskList
}
submit(formValue){
console.log(formValue)
}
clientForm = this.fb.group({
custom : this.fb.array([this.fb.group({
clientTaskId: [''],
taskName: [''],
billableRate: [''],
customRate: ['']
})]),
customRate: ['']
})
constructor(private fb: FormBuilder ) { }
}
这里是演示:demo在此演示中,我给ng-select标记指定了formControlName而不是formArray名称,以使您理解我的要求。
因此,我选择的任何对象都应加载在formArrayName中。我尝试了对ng-select添加(更改)功能,但给出了不同的答案。
谢谢。
答案 0 :(得分:0)
您是否尝试将formArrayName放在div中向上一个级别?
<div formArrayName="custom">
<ng-select>...</ng-select>
</div>
如果我正确阅读,则您的选择应该绑定到数组中的特定formControlName