I am loading my array of objects response into a multiselect (ng-select). My response is like this
The formModel is like this
clientForm = this.fb.group({
custom : this.fb.array([this.fb.group({
clientTaskId: [''],
taskName: [''],
billableRate: [''],
customRate: ['']
})]),
})
When I select the options in multi-select, I am not able to get the value in the formArrayName 'custom'. But when I use 'custom' as a 'formControlName' I am able to get the objects which ever I am selecting.
Here is my code :
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 ) { }
}
Here is the demo : demo In this demo I have given the ng-select tag with formControlName and not as formArray name to make you understand my requirement.
So, what ever object I select should be loaded in the formArrayName . I tried the adding (change) function to the ng-select but it gave a different answer.
Thanks in advance.