简体   繁体   中英

Can we use Angular FormArray with angular2-multiselect dropdown?

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

StackBlitz link

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> &nbsp;

  <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>

You had to remove the [(ngModel)] since you are using reactive forms

  <angular2-multiselect [data] = "tasksData" 
    [settings] = "tasksDropDownSettings"
    formControlName="task">
  </angular2-multiselect>

Working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM