Angular checkboxes not updating with current values when submitted

I have defined a static array in TypeScript like this:

  permissions: any[] = [
    { permission: "Read", enabled: true },
    { permission: "Write", enabled: false },
    { permission: "Delete", enabled: false },
    { permission: "Edit", enabled: true }
  ]

In my HTML, I am looping through and displaying checkboxes for each item. The checkboxes that are true should be checked by default. However, when I change the value of the checkbox, it still reflects the initial values from TypeScript instead of the updated ones.

<h4 *ngFor="let p of permissions">
 <input type="checkbox" [checked]="p.enabled">{{p.permission}}
</h4>
<button (click)="updatePermissions(permissions)">Update</button>

In the TypeScript file, I am logging the permissions to the console.

 updatePermissions(permissions){
    console.log(permissions);
}

Answer №1

To properly bind data, you must use ngModel.

<h4 *ngFor="let r of rights">
 <input type="checkbox" [(ngModel)]="r.value">{{r.right}}
</h4>
<button (click)="go(rights)">Update</button>

Don't forget to include FormsModule in your module for [(ngModel)] to function correctly.

Answer №2

The reason your code is not functioning correctly is because you have used the wrong type of data binding.

Data binding serves as a method to synchronize what users see and interact with in relation to specific data. By establishing bindings between sources of data and HTML elements, the framework can handle the necessary tasks.

Angular offers various forms of data binding, and in this particular instance, you needed to utilize a Two-way data binding. This essentially means that any modifications made to the target element will update the source, and vice versa - changes to the source data update the visible value of the target element.

Two-way data binding operates through both Interpolation and Event.

To resolve this issue, simply adjust the checkboxes using the following syntax:

<input type="checkbox" [(ngModel)]="r.value"> {{r.right}}

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

ngIf failing to pick up on variable updates

Utilizing the greensock animation library to animate various components has presented a problem during the variable update within the onComplete function linked to a *ngIf. Strangely, Angular fails to recognize the variable update within the callback. Des ...

When you use array[index] in a Reduce function, the error message "Property 'value' is not defined in type 'A| B| C|D'" might be displayed

Recently, I delved deep into TypeScript and faced a challenge while utilizing Promise.allSettled. My objective is to concurrently fetch multiple weather data components (such as hourly forecast, daily forecast, air pollution, UV index, and current weather ...

Encountering an Unexpected Token in Angular 15, API 29 App

Upon attempting to build and run my Angular application on an Android 10 (API 29) emulator, I encounter a white screen on the device along with the following error message in Android Studio: E/Capacitor/Console: File: http://localhost/ - Line 610 - Msg: Sy ...

Troubleshooting issue with Angular-CLI and Cordova plugin integration

While attempting to build an Angular 4 app using ng-build, I encountered an error when trying to access device.uuid: /navigation.component.ts (14,5): Cannot find name 'device'. Every plugin referenced in TS files is triggering this error. I a ...

Having trouble executing ng build --prod in Azure CICD pipelines

Having trouble setting up my application's CI/CD in Azure as the build process keeps failing. I've gone through my YAML configuration and tried multiple solutions found online, but it still doesn't work. This is the YAML setup I have: ...

Guide on resolving the error "Type 'Emits' does not have any call signatures" in Vue 3 with the combination of script setup and TypeScript

I've come across some code that seems to be functioning properly, but my IDE is flagging it with the following warnings: TS2349: This expression is not callable. Type 'Emits' has no call signatures Below is the code snippet in question: ...

The AppModule's CanLoad protector

I recently developed an Angular application using angular-cli and successfully implemented CanLoad guard for my modules. The CanLoad check verifies if the user is logged in before loading a module. My question is, can I apply CanLoad guard to AppModule as ...

The backend GET request functions properly on Postman, but fails to return any data to the frontend

When making a GET request and adding the creator as a parameter like api/watchlist/?creator=5dac9d3567aca81e40bfc0, all posts by that creator are returned in Postman with the following code: app.js app.get('/api/watchlist',(req, res, next)=&g ...

What could be causing the sidebar animation to glitch in Internet Explorer when using an *ngFor loop?

I am facing an issue with my animation where it works perfectly in Chrome but not in IE. The desired effect is to slide a panel into view from outside the browser window, and upon clicking the exit button or <div> covering the rest of the page, the p ...

What are the steps for deploying an Angular 2 project to a server with PUTTY?

After developing an Angular 2 app with Angular-CLI on my local server, I have reached the production phase and now need to upload it to a CentOS server using Putty. I attempted to follow instructions from this source for installing node and npm on the ser ...

Techniques for adding data to an array using TypeScript

I am working on a project that involves creating a dynamic menu bar by fetching data from two different collections (supcat and cat) in order to combine them into a new array. However, I am encountering an issue with the push() method not working as expe ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

Guide to exporting everything within a div as a PDF using Angular 2

When attempting to convert a div with the id "div1" into a PDF using JSPdf in Angular 2, everything seems to be working fine until I try to export it to PDF. Here is my code snippet: <div class="container" id="div1"> <table> <tr> & ...

When attempting to import the image path from a JSON file, a ReferenceError occurs stating that the data variable is not

I'm currently attempting to iterate through image paths in a JSON file and display them in a browser using the "img" tag. While hardcoded values work perfectly fine, I encountered an issue when trying to switch to a variable as outlined in this post: ...

Utilizing a service within NestJS

I'm currently in the process of updating some older code and I have created a service that I want to inject into the constructor of a class. There are two key points to consider about this particular class. The first point is that it is instantiated b ...

Acessing files from Azure Blob within the Aurelia UI: Download or View now!

I currently have my files stored in Azure and I am looking for a way to either download or view them on the client side. This is how I envision the process: Azure -> Api -> Client UI (Aurelia) While I have come across several C# examples, I am unsu ...

Struggling to convert my VueJS component from JavaScript to TypeScript, feeling a bit lost

I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no er ...

Angular Service Worker: 504 error encountered during application deployment refresh

After building my Angular 8 project with ng build --prod, I serve it from the /dist folder using http-server. The app still works even after stopping it thanks to the service worker. The project successfully registers its service worker and I am able to ...

What is the best way to apply multiple array filters to an object list in react.js?

Looking to filter an array of items using multiple filter arrays in order to display only the items that match all selected filters. For example: The main array contains a table with the following data: ID TypeID LocationID Name 1 2 ...

Develop a fresh category inspired by the properties of objects

Let's tackle the challenge of constructing a new type in Typescript based on an descriptive object named schema, which contains all the requirements expressed within it. Here is my proposed solution: type ConfigParameter<IdType, ValueType> = Re ...