The Primeng Angular2 checkbox malfunctioning issue

My form setup in Angular2 CLI looks like this:

Inside the component

export class UsersAddComponent implements OnInit {

 ngOnInit() {
    this.userForm = this._formBuilder.group({
      role: ['', [Validators.required]],
      others: this._formBuilder.array([])  //for adding multipe form inputs
    });

   this.addNewUser();

  }

  initAddress() {
     return this._formBuilder.group({     
       sendcred: [''],  //checkbox needs no validation in my logic
        needs_reset: [''], // ''
        .....other fields here
    });
 }


  addNewUser() {  //this is called whenever add new user button is clicked
     const control = <FormArray>this.userForm.controls['others'];
     const addrCtrl = this.initAddress();
     control.push(addrCtrl);
   }

In the HTML template, I'm using PrimeNG checkboxes like this:

  <p-checkbox formControlName="needs_reset" label="User has to set password" 
   (onChange)="Onpwdchange()"></p-checkbox>

  <p-checkbox formControlName="sendcred" name="send cred"  label="Send user
 login credentials " (onChange)="Oncredchange()"></p-checkbox>

The methods onpwdchange() and oncredchange() simply have a console.log("clicked")

However, when I check the checkboxes, I encounter an error:

this.model.push is not a function  //i havent implemented push method anywhere

I've looked into This Primeng2 issue but their suggested solutions of disableDeprecatedForms() and provideForms() are not available in Angular2 CLI.

How can I resolve this problem?

Answer №1

As per the documentation provided by PrimeNG

https://www.primefaces.org/primeng/#/checkbox

The formControlName attribute does not function properly with PrimeNG's checkbox component.

Therefore, you should follow this approach instead

<p-checkbox value="xyz" [formControl]="myFormGroup.controls['name']"></p-checkbox>

If you require a binary value of true or false

<p-checkbox binary="true" [formControl]="myFormGroup.controls['name']"></p-checkbox>

Answer №2

  1. Set up initial form values by

file.ts

this.infraestructuraServiciosForm = this.fb.group({
     ....
     complementarios : new FormControl('', []),
     ......
});
  1. To prevent errors, add the following line:

    this.infraestructuraServiciosForm.controls['complementarios'].setValue([]);
    

file.html

<p-fieldset legend="Complementary Options">
            <body>
                <div class="ui-g ui-fluid">
                     <div class="ui-g-12">
                        <div class="ui-g-3">
                            <p-checkbox name="cpl" value="sidewalksCurbs" label="Sidewalks and Curbs" formControlName="complementarios" (onChange)="handleSidewalksCurbsChange(checked)"></p-checkbox>
                        </div>
                        <div class="ui-g-3">
                            <p-checkbox name="cpl" value="onlyCurbs" label="Only Curbs" formControlName="complementarios" (onChange)="handleOnlyCurbsChange(checked)"></p-checkbox>         
                        </div>
                        <div class="ui-g-3">
                            <p-checkbox name="cpl" value="landline" label="Landline Network" formControlName="complementarios"></p-checkbox>      
                        </div>          
                        <div class="ui-g-3">
                            <p-checkbox name="cpl" value="publicLighting" label="Public Lighting" formControlName="complementarios"></p-checkbox>                              
                        </div>
                    </div>                                     
                </div>
            </body>
        </p-fieldset>

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

After updating to Angular 9, the ViewChild functionality seems to be malfunctioning

Is there a change in ViewChild behavior? Since upgrading to Angular 9, the MatSideNav menu has ceased to function. export class SidenavOpenCloseExample implements OnInit, AfterViewInit { @ViewChild('menuSide', {read: MatSidenav, static: true} ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

What should be used in Angular 2 Reactive Forms - controls or get()?

Lately, in templates, I've come across two different approaches: myForm.controls.StartDate.value and myForm.get('StartDate').value I initially thought that 'controls' was the recommended approach moving forward. However, when r ...

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

Angular will continue to stay on the current page unless the form is completed

Once a user logs in, they are directed to a form where they can enter their name and username. http://localhost:4200/form I need to ensure that the user fills out the form before being redirected to another page, even if they try to change the URL. In m ...

Tips for overlaying text on an image in html with the ability to zoom in/out and adjust resolution

My challenge is aligning text over an image so that they move together when zooming in or out. However, I am facing difficulties as the text and image seem to move in different directions. I have attempted using media queries and adjusting the positions of ...

Issue with Angular Router: unable to retrieve route parameters in child paths

Within our main app.component routing, we have the following setup: { path: 'store', loadChildren: './store/store.module#StoreModule', canActivate: [LoginGuard] }, Then, in the module, our routes are defined as follows: const routes: ...

Tips for validating an object with unspecified properties in RunTypes (lowercase object type in TypeScript)

Can someone please confirm if the following code is correct for validating an object: export const ExternalLinks = Record({}) I'm specifically asking in relation to the repository. ...

What is the best way to create a React text box that exclusively accepts numeric values or remains empty, and automatically displays the number keypad on mobile devices?

While there are numerous similar questions on StackOverflow, none of them fully address all of my requirements in a single solution. Any assistance would be greatly appreciated. The Issue at Hand Within my React application, I am in need of a text box tha ...

What is the best method to adjust the width of the PrimeNG ConfirmDialog widget from a logic perspective

Currently utilizing "primeng": "^11.2.0" and implementing the ConfirmDialog code below this.confirm.confirm({ header: 'Announcement', message: this.userCompany.announcement.promptMsg, acceptLabel: this.userCompany.announcement ...

What is preventing MenuItemLink from being displayed in the menu?

I have created a unique page for users to purchase subscriptions, but I am having trouble accessing that page because the button is not appearing in the menu. I followed the steps outlined in the official guide, but only the dashboard and resources buttons ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

Error: Unable to access the 'nativeElement' property because it is undefined - occurring during the ngAfterViewChecked lifecycle hook

I am facing issues with some of my karma jasmine unit tests failing after adding an ngAfterViewChecked. Despite initializing the "mySwitchEl" as shown below, the error persists. @Component({ selector: 'my-component', templateUrl: '. ...

Embedding content within various ng-template elements

I'm currently working on developing a button component (app-button) that can utilize multiple templates based on the parent component using it. <div class="ds-u-margin-left--1 ds-u-float--left"> <ng-container *ngTemplateOutlet="icon">< ...

Efficiently integrating Firebase Functions with external sub path imports beyond the project's

I encountered an issue in my firebase functions project with typescript. The problem arises when I use types from outside the project with sub path imports, causing the build files to become distorted. Instead of having main:lib/index.js, I have main:lib/ ...

The implementation of Typescript in Express does not rely on Middleware

I've encountered an issue with my Auth Middleware - it seems that the middleware isn't being called at all. Even when I intentionally throw an Error within the middleware function, nothing is printed out. For testing purposes, I only need to inv ...

I obtained the binary tree output in the form of an object. How can I extract the values from this object and store them in an array to continue working on

Issue Statement In this scenario, you have been presented with a tree consisting of N nodes that are rooted at 1. Each node in the tree is associated with a special number, Se. Moreover, each node possesses a certain Power, which is determined by the count ...

Generating a new object using an existing one in Typescript

I received a service response containing the following object: let contentArray = { "errorMessages":[ ], "output":[ { "id":1, "excecuteDate":"2022-02-04T13:34:20" ...

Client side is receiving an unexpected format from the pyramid when using the __json__ method

As I'm configuring a Pyramid back-end along with an Angular front-end application, I encounter an issue. When Angular sends an http GET request to Pyramid, the data received on the Angular side is not as expected. It seems like the id is being recogni ...

In the CallableFunction.call method, the keyword "extends keyof" is transformed into "never"

In the following method, the type of the second parameter (loadingName) is determined by the key of the first parameter. (alias) function withLoading<T, P extends keyof T>(this: T, loadingName: P, before: () => Promise<any>): Promise<void ...