对于我的用例,我必须构建一个表单,以便我们可以动态地将行添加到表单列中。我使用 Angular FormArray 构建了它。在该表单中,我必须添加一个下拉列表,用户可以在其中选择任务并可以从任务列表中搜索指定的任务。所以我尝试使用 angular2-multiselect 下拉菜单。 当我添加新行时,前一行下拉列表选定的值将在新添加的行中更新。谁能帮我解决这些问题吗?
这里我包含了带有错误的示例代码
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>
最佳答案
由于您使用的是响应式(Reactive)表单,因此必须删除 [(ngModel)]
<angular2-multiselect [data] = "tasksData"
[settings] = "tasksDropDownSettings"
formControlName="task">
</angular2-multiselect>
关于javascript - 我们可以将 Angular FormArray 与 angular2-multiselect 下拉菜单一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59385720/