Utilizing PrimeNG checkbox groups in a reactive form: A guide to retrieving all selected values

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

Answer №1

According to the official documentation (Model Driven Forms section), it is suggested to bind the formControl instance instead of using the formControlName attribute.

<!-- Incorrect -->
<p-checkbox formControlName="cities"></p-checkbox>

<!-- Correct -->
<p-checkbox [formControl]="myFormGroup.controls['cities']"></p-checkbox>
<p-checkbox
  name="group1"
  value="New York"
  [formControl]="searchForm.get('selectedCities')"
  inputId="ny"
></p-checkbox>

Live Demo on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

Navigating with Angular inside an HTTP POST Observable and subscription

Whilst attempting to guide a user towards a dashboard within the response of an httpClient.post request, I have encountered a peculiar issue. The page navigates "successfully" (as evidenced by the URL bar) but unfortunately, most elements of the components ...

"Exploring the depths of Webpack's module

This is my first venture into creating an Angular 2 application within MVC Core, utilizing TypeScript 2.2, Angular2, and Webpack. I have been closely following the Angular Documentation, but despite referencing the latest NPM Modules, I encounter errors w ...

challenge communicating between Angular and Node using CORS plugin

I've been researching how to enable CORS in node/express and have tried implementing various solutions, but without any success. Here is my angular request: function getPhotos(location) { var url = 'https://api.instagram.com/v1/media/sear ...

The Angular Material Table Collapse feature offers dynamic collapsing similar to jQuery Datatable

Is there a way to improve the appearance of my Angular Material Table, especially on mobile? https://i.stack.imgur.com/sZXPP.png The current display of my Angular Material Table is not aesthetically pleasing when viewed on mobile devices. https://i.stack ...

Retrieve selected button from loop typescript

https://i.stack.imgur.com/DS9jQ.jpgI have an array of individuals that I am looping through. It's a bit difficult for me to explain, but I want something like this: <div *ngFor="let person of persons"> {{person.name}} {{person.surname}} <but ...

Display a unique element depending on the path of the Dynamic Angular Routing

Here are the routes I am working with: /dashboard /dashboard/view-all /dashboard/edit/:id One specific issue I've encountered is related to showing/hiding the EditComponent based on the dynamic router. Typically, I can show/hide Angular components ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Tips on incorporating toggle css classes on an element with a click event?

When working with Angular typescript instead of $scope, I am having trouble finding examples that don't involve $scope or JQuery. My goal is to create a clickable ellipsis that, when clicked, removes the overflow and text-overflow properties of a spec ...

The chosen option from the dropdown menu fails to register as selected

In my Angular 8 application, I am facing an issue with a dropdown list. The data for the dropdown list is fetched from the backend. However, when I select a value from the dropdown list, it remains undefined or not selected. Interestingly, if I manually ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

Removing a portion of an item with the power of RxJS

I possess the subsequent entity: const myObject = { items:[ { name: 'John', age: 35, children: [ { child: 'Eric', age: 10, sex: 'M' }, { ...

Troubleshooting Angular Build Errors: Integrating Three.js

Upon setting up a new Angular application and integrating three along with @types/three, I proceeded to create a basic component. However, upon executing ng build --prod, the following errors are displayed: ERROR in node_modules/three/src/core/BufferAttri ...

Creating a grid UI in AngularJS using Typescript: utilizing functions as column values

I am working on an AngularJS app that includes the following UI grid: this.resultGrid = { enableRowSelection: true, enableRowHeaderSelection: false, enableHorizontalScrollbar: 0, enableSorting: true, columnDefs: [ { name: &apos ...

Unable to successfully install Angular CLI through npm

Having trouble installing Angular CLI with the command npm install @angualr/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5c53567f0e1108110a">[email protected]</a>. I encountered the error shown in the screen ...

Tips for structuring TypeScript with MobX in a ReactJS project

I created a MobX store as shown below. I defined the types of actions in store.js import { action, observable } from 'mobx'; export class SignStore { @observable UserInformation: { email: ''; password: ''; ...

The replacer argument of the JSON.stringify method doesn't seem to work properly when dealing with nested objects

My dilemma is sending a simplified version of an object to the server. { "fullName": "Don Corleone", "actor": { "actorId": 2, "name": "Marlon", "surname": "Brando", "description": "Marlon Brando is widely considered the greatest movie actor of a ...

Challenge when providing particular strings in Typescript

Something seems to be wrong with the str variable on line number 15. I would have expected the Typescript compiler to understand that str will only ever have the values 'foo' or 'bar' import { useEffect } from 'react' type Ty ...

TRPC error: The property 'useInfiniteQuery' is not found in the type '{ useQuery'

Issue with TRPC I am facing a problem with my tweetRouter that has a timeline query returning tweets and a NextCursor. However, I encounter an error when trying to access useInfiniteQuery in my components. ** Property 'useInfiniteQuery' does no ...

The FullCalendarModule does not have a property named 'registerPlugins' in its type definition

Currently in the process of integrating fullcalendar into my Angular 15 project and encountering the following error: Error: src/app/views/pages/takvim/takvim.module.ts:18:20 - error TS2339: Property 'registerPlugins' does not exist on type &apo ...