Leveraging ngModel for automated validation of PrimeNG checkbox

I have a set of checkboxes that are generated dynamically. Based on the data, certain checkboxes should be pre-selected. For some reason, ngModel is not achieving this.

Template:

<div *ngFor="let option of options">
     <p-checkbox [(ngModel)]="selectedOption"
                 [value]="option.value"
                 name="option-row">
     </p-checkbox>
</div>

Component:

...

selectedOption!: string | undefined;

getOptions() {
      this.apiService.getOptions()
       .pipe(
           take(1),
           tap(() => // logic to check if getOptions() response includes 
                     // an existing value that matches potential options 
                     // (checkboxes)
       ).subscribe(noop)
}

In the tap() method, I am checking if a specific value property exists. The code snippet here is a shortened version for demonstration purposes. If it does exist, I assign that value to this.selectedOption. These values correspond to the checkbox values, but even when this.selectedOption is set, the checkbox remains unchecked.

In scenarios where the checkbox should be pre-checked, the [(ngModel)] doesn't seem to capture the updated value of this.selectedOption.

Answer №1

To ensure a unique name, add an index to the ngFor loop like

*ngFor="let value of values; let i = index"
and then incorporate this index into the name attribute like
[name]="'value_row_' + i"
. This will prevent conflicts as each name will be unique. Avoid using a minus sign in the name, stick to underscores instead. I will verify this by testing it on StackBlitz later when I have access to my computer.

There are some issues present here - all checkboxes are being bound two-way to the same value. This means that if one checkbox is updated, it will update all checkboxes simultaneously since they are all connected to the same value.

Answer №2

To display the chosen values in checkboxes based on this.existingValue, it should be of type array of strings: this.existingValue : string []. Fill this array with values returned by the getValues() method. Additionally, remember to include a label to show the value:

<label for="'value-row_' + i">{{value}}</label>

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

Tips for executing forEach on a promise?

I am currently working with a function that returns a promise of an array: async function functionReturningPromiseOfUserIDs(): Promise<string[]> My question is, can I use the forEach method on the array returned by this function? async function runF ...

What exactly is happening with this Plunkr code?

When variables or expressions are used within brackets [] in Angular, what is the scope of these variables? In the Plunkr code provided below, the variable helloWorld is defined in the rio-app but utilized in the rio-hello. Does Angular search all the way ...

Issue with Angular 2's event emitter malfunctioning

I have a dashboard component and a bottom-nav component. When the setting icon in the bottom-nav component is clicked, I want an alert to appear in the parent dashboard component. Here is the code: dashboard.component.ts ===== html part ====== <div cl ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

Ensuring that the STOMP socket connection is successfully established prior to subscribing to any data

Working on my Angular 2 project, I utilized the ng2-stomp-service to establish a socket connection with the server. While it mostly runs smoothly, there are instances where an error occurs when attempting to subscribe to the socket. The error message indi ...

Just recently updated to Angular 14 and I'm encountering a problem with images not loading from the assets folder. I'm wondering if there is a configuration step I missed. Could someone please

https://i.stack.imgur.com/4LEQ4.png https://i.stack.imgur.com/3sxzF.png Is there a configuration missing in Angular 14? When I try using <img [src]="assets/images/sidebarNav"> with ./, ../, it doesn't work. I have followed the instr ...

What is the process for generating a dynamic array in typescript?

Looking to create a TypeScript dynamic array with the desired format: const display = [ { id: 1, displayName: "Abc1" }, { id: 2, displayName: "Abc2" }, { id: 3, displayName: "Abc3" } ] Attempted the following code ...

I'm interested in creating a unique form validator in Angular that verifies if a string has a combination of letters and numbers. How can this be

Currently, I am developing a registration form within Angular that mandates users to create a password comprising of both letters and numbers. I am in need of embedding a personalized validator to uphold this regulation. What would be the most practical ap ...

Problem with TypeScript involving parameter destructuring and null coalescing

When using parameter destructuring with null coalescing in TypeScript, there seems to be an issue with the optional name attribute. I prefer not to modify the original code like this: const name = data?.resource?.name ?? [] just to appease TypeScript. How ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

Should UI conditional changes always be placed directly within the class?

Currently, the class is undergoing changes in color schemes. When the value is set to active, it displays colored text and background accordingly. The same logic applies to other values like rejected, cancelled, expired, and pending. Is this the most eff ...

"Encountering an unmet peer dependency error while trying to set up Angular2 through the package.json

Suppose I have a fresh project with the following package.json setup: { "name": "EmptyNG2", "version": "1.0.0", "description": "Empty Description", "repository": {}, "dependencies": { "angular2": "^2.0.0-beta.17" }, "author": "me", "li ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

The displayed session in the Ionic App component.html is not appearing

When attempting to display a session in HTML named {{nama_cust}} on app.component.html, I encountered an issue where nothing appeared or it showed up blank. Is there an error in the code? Or is it possible that the app.component cannot process sessions? He ...

Creating a simulated constant class in Angular 2+ for handling environment variables

Can anyone assist me with writing unit tests for functionalities that depend on the current environment? I am struggling to force a constant environment to return specific values in my source code. Here is the component code I need to test: import { Compo ...

Has an official Typescript declaration file been created for fabric.js?

Currently, I have come across a Typescript definition for fabric.js on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fabric (https://www.npmjs.com/package/@types/fabric). However, its official status is unclear. Does anyone have more ...

Tips for implementing validation in template-driven form using Ionic 3

How can I validate a mobile number in an Ionic 3 application? I am using ngModel, but I'm looking for an example to help me with the validation process. Can anyone provide guidance on how to do this? <ion-list> <ion-item margin ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

The application of Angular's extension may experience functionality issues due to a failed ngcc operation

https://i.stack.imgur.com/Q7eFX.png The current issue I am encountering. https://i.stack.imgur.com/Kj1r0.png However, the command ng serve is functioning smoothly without any errors. https://i.stack.imgur.com/0SluL.png I'm also facing this partic ...

tips for deactivating routerLink functionality on anchor elements

Working on an Angular application that requires me to create an image slider. However, due to the presence of router links in the application, the anchor tags in the image slider keep redirecting. I want to prevent this redirection and instead successful ...