I'm working on an Angular project where I need to implement a form that includes a FormArray with multiple FormControl instances, each using PrimeNG's Autocomplete component with multiple selection enabled. I'm having trouble figuring out how to bind the selected values from the Autocomplete component to the FormArray.
Here's a simplified version of what I'm trying to achieve:
I have a FormArray that dynamically generates a list of FormControl instances.
Each FormControl should be associated with a PrimeNG Autocomplete component that allows multiple selections.
When the user selects multiple items from the Autocomplete, those selected items should be stored in the corresponding FormControl.
Here's a snippet of my current setup:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
suggestions: any[] = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
items: this.fb.array([this.createItem()])
});
}
createItem(): FormGroup {
return this.fb.group({
selectedItems: new FormControl([])
});
}
get items(): FormArray {
return this.myForm.get('items') as FormArray;
}
addItem() {
this.items.push(this.createItem());
}
removeItem(index: number) {
this.items.removeAt(index);
}
}
And the corresponding HTML:
<form [formGroup]="myForm">
<div formArrayName="items">
<div *ngFor="let item of items.controls; let i = index" [formGroupName]="i">
<p-autoComplete
formControlName="selectedItems"
[suggestions]="suggestions"
[multiple]="true"
(completeMethod)="filterSuggestions($event)"
field="name">
</p-autoComplete>
</div>
</div>
<button type="button" (click)="addItem()">Add Item</button>
</form>
How do I properly bind the selected values from the PrimeNG Autocomplete component to the FormControl within the FormArray?
Is there a specific way to handle the completeMethod to filter suggestions dynamically for each FormControl in the FormArray?
Are there any common pitfalls or best practices when using PrimeNG Autocomplete with Angular's reactive forms, especially with FormArray?
Any help or guidance would be greatly appreciated! Thanks in advance.