I am facing an issue with a group of <p-checkbox>
elements from PrimeNG. They all have the same name
and formControlName
attributes. The form control's value is an array, but it seems to only retain the selection of the last checkbox clicked.
TS:
import { Component, OnInit } from '@angular/core';
import { MenuItem } from 'primeng/api';
import {
FormGroup,
Validators,
FormControl,
FormBuilder,
} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
constructor(private formBuilder: FormBuilder) {}
searchForm: FormGroup;
ngOnInit() {
this.searchForm = this.formBuilder.group({});
this.searchForm.addControl('selectedCities', new FormControl([]));
}
}
HTML:
<h5>Basic</h5>
<form [formGroup]="searchForm">
<h5>Multiple</h5>
<div class="p-field-checkbox">
<p-checkbox
name="group1"
value="New York"
formControlName="selectedCities"
inputId="ny"
></p-checkbox>
<label for="ny">New York</label>
</div>
<div class="p-field-checkbox">
<p-checkbox
name="group1"
value="San Francisco"
formControlName="selectedCities"
inputId="sf"
></p-checkbox>
<label for="sf">San Francisco</label>
</div>
<div class="p-field-checkbox">
<p-checkbox
name="group1"
value="Los Angeles"
formControlName="selectedCities"
inputId="la"
></p-checkbox>
<label for="la">Los Angeles</label>
</div>
<div class="p-field-checkbox">
<p-checkbox
name="group1"
value="Chicago"
formControlName="selectedCities"
inputId="ch"
></p-checkbox>
<label for="ch">Chicago</label>
</div>
</form>
<p *ngFor="let city of searchForm.get('selectedCities').value">{{ city }}</p>
Check out my StackBlitz project: https://stackblitz.com/edit/primeng-checkbox-demo-23nqc7?file=src%2Fapp%2Fapp.component.ts