Reputation: 274
For my usecase, i have to build a form in that we can dynamically add rows to the form columns. I built that using Angular FormArray. In that form, i have to add a dropdown, where user can select the task and can search for the specified task from the tasks list. So i tried with angular2-multiselect dropdown. When i am adding a new row the previous row dropdown selected value is updating in the newly added row. Can anyone help me on these?
Here i am including sample code with the error
form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, FormArray } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent implements OnInit {
tasksDropDownSettings = {};
selectedTasks = [];
constructor(private fb: FormBuilder) { }
todoForm : FormGroup;
tasksData = [
{id: 1, taskName: "Go for Jogging"},
{id: 2, taskName: "Complete the work"},
{id: 3, taskName: "Catch the bus"},
{id: 4, taskName: "Leave by 6"}
]
ngOnInit() {
this.todoForm = this.fb.group({
tasks: this.fb.array([this.fb.group({task:''})])
})
this.tasksDropDownSettings = {
singleSelection: true,
enableSearchFilter: true,
text: "Select Primary Skill",
showCheckbox: true,
labelKey: 'skillName',
selectAllText:'Select All',
unSelectAllText:'UnSelect All'
}
}
get tasks() {
return this.todoForm.get('tasks') as FormArray;
}
addTask() {
this.tasks.push(this.fb.group({task:''}));
}
* form.component.html *
<form [formGroup] = "todoForm">
<label> Add tasks here </label>
<div formArrayName = "tasks">
[enter image description here][1]
<div *ngFor="let item of tasks.controls; let taskIndex=index" [formGroupName]="taskIndex" (click) = "onClick(tasks.controls)">
<angular2-multiselect [data] = "tasksData"
[(ngModel)] = "selectedTasks"
[settings] = "tasksDropDownSettings"
formControlName="task">
</angular2-multiselect>
</div>
</div>
<button type = "submit" class = "btn btn-submit"> Save </button>
<button (click) = "addTask()"> Add Row </button>
</form>
<pre>{{ this.todoForm.value | json }}</pre>
Upvotes: 0
Views: 2155
Reputation: 1325
You had to remove the [(ngModel)] since you are using reactive forms
<angular2-multiselect [data] = "tasksData"
[settings] = "tasksDropDownSettings"
formControlName="task">
</angular2-multiselect>
Upvotes: 1