Unable to programmatically uncheck a checkbox after it has been manually checked: Angular

After being selected through the UI by clicking on the checkbox, I am encountering an issue where I cannot unselect the checkbox programmatically.

To see this behavior in action, visit the sample app, where you can click on the checkbox to select it and then click on the 'Un Check' button. Despite the property in the background switching to false, the checkbox remains selected.

Please note:

If the checkbox is not manually selected, both selecting and deselecting works as expected when done programmatically.

For further exploration, you can access the code editor here.

Answer №1

In the provided code snippet, the usage of input [checked] indicates a one-way binding.

To achieve two-way binding or to be more specific, the ability to both retrieve and set the value, you may require a setter function along with your existing logic.

  • If you opt not to utilize ngModel as demonstrated in the current code, consider utilizing the (change) event to update the value together with a setter function:

    get IsChecked(): boolean {
      return this._isChecked;
    }
    set IsChecked(val) {
      this._isChecked = val;
    }
    

    The corresponding HTML implementation would be:

    <input type="checkbox" [checked]="IsChecked" (change)="IsChecked = !IsChecked"/>

  • Alternatively, you can also make use of ngModel.

<input type="checkbox" [(ngModel)]="IsChecked"/>
which further expands to:

<input type="checkbox" [ngModel]="IsChecked" (ngModelChange)="IsChecked = !$event"/>
providing similar functionality to [checked] combined with (change) events

Answer №2

Modify the input in app.component.html to look like this:

<input type="checkbox" [checked]="IsChecked" (change)="onCheckedChanged()" />

and include the following code in your app.component.ts:

  onCheckedChanged() {
   this._isChecked = !this._isChecked;
  }

The Reasoning Behind the Changes:

Although you correctly bound the checked attribute to the IsChecked getter, it only updates when changes occur to IsChecked, which is why the checkboxes were not functioning properly.

When clicking on the checkbox itself, the IsChecked property does not change, hence the need to actively listen for the change event and update the IsChecked (or rather the this._isChecked) property through code.

Additionally, it is common practice in Typescript and Angular to begin class fields with a lowercase letter based on the usual conventions.

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

Definitions provided for Redux (Toolkit) store including preloadedState

I'm currently working on setting up typings for configuring a Redux store with a preloaded state. While following the Redux Toolkit TypeScript quick start guide, I came across this example: import { configureStore } from '@reduxjs/toolkit' ...

Using TypeScript to assert the type of a single member in a union of tuples, while letting TypeScript infer the types of the other members

Currently, I am attempting to implement type assertion for the "error-first" pattern. Within my function, it returns tuples in the format of ['error', null] or [null, 'non-error']. The specific condition I want to check for is error = ...

Dealing with Nested Body Payload in PATCH Requests with Constructor in DTOs in NestJS

Within my NestJS environment, I have constructed a DTO object as follows: export class Protocol { public enabled?: boolean; public allowed?: boolean; constructor(enabled: boolean, allowed: boolean) { // With a necessary constructor this.enabled = ...

I keep receiving multiple header errors from ExpressJS even though I am positive that I am only sending a single header

Can someone please help with the issue I'm facing in the code below: router.put("/:_id", async (req: Request, res: Response) => { try { // Create the updated artist variable const artist: IArtist = req.body; const updatedArt ...

Issue with installing angular CLI on Windows 10

Having trouble installing Angular CLI with npm on a Windows 10 system I've exhausted all possible solutions Attempted clearing the cache and re-running the installation command - npm install -g @angular/cli - but encountered new errors every tim ...

Having trouble with the npm Fluid Player installation

I am attempting to integrate Fluid Player into my Angular application Using - npm i fluid-player However, I'm encountering this error ...

Tips for composing content on a sanitized input?

In my small application, I have a feature where a question is displayed with certain words hidden and needs to be filled in by the user. The format of the question looks like this: The {0} {1} {2} his {3} off To achieve this functionality, I wrote the f ...

Unable to initialize the ng2-admin Angular2 Bootstrap template on a Go server due to a failed download attempt

Hello everyone, I am a newcomer to this forum and have limited experience with Angular2 and Golang. I am currently facing an issue as I want to experiment with a template on a Go server. To tackle this, I created a main.go file that includes the followin ...

The utilization of angular2-materialize is not possible due to an error message indicating that jQuery.easing is undefined

Greetings to all who are taking the time to read this. I am encountering an issue while trying to run ng serve. Here is the error message I am receiving: TypeError: jQuery.easing is undefined Here is a breakdown of what I have done so far: ng new X cd X ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

What is the abbreviation for a 'nested' type within a class in TypeScript?

Consider the TypeScript module below: namespace AnotherVeryLongNamespace { export type SomeTypeUsedLater = (a: string, b: number) => Promise<Array<boolean>>; export type SomeOtherTypeUsedLater = { c: SomeTypeUsedLater, d: number }; } cl ...

Utilizing a background image property within a styled component - Exploring with Typescript and Next.js

How do I implement a `backgroung-image` passed as a `prop` in a styled component on a Typescript/Next.js project? I attempted it in styled.ts type Props = { img?: string } export const Wrapper = styled.div<Props>` width: 300px; height: 300px; ...

Achieve perfect alignment of Bootstrap checkboxes

Is there a way to vertically align checkboxes in a column with their labels? My goal is to have these elements centered on the page, but I want the checkboxes themselves to be aligned vertically. <div class="row"> <div class="span12 paginatio ...

Is there a way to trigger the opening of the mat-autocomplete panel when an option is selected in a different mat-autocomplete component?

Is it possible to trigger the opening of a mat-autocomplete panel when an option is selected in another mat-autocomplete? To see an example, please check out this demo. ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

Angular2 Components with Unique Styling

I am working on an Angular2 app that includes several components, some of which I want to reuse multiple times on a single page. Instead of having three separate components, I am looking to refactor and combine their functionalities into one. The basic st ...

The ability to choose only one option in a checkbox within a grid view column

In my grid view, I have a checkbox in the last column. I am trying to ensure that only one row can be selected at a time. <tr *ngFor="let permit of PermitDetails" (click)="GoByClick(permit)"> <td style="text-align: center">{{permit.TVA_BAT ...

The Angular component fails to load in the browser because of a problem with the Observable subscription

Whenever I try to execute the getCurrentSalahOrIqamah function in the ngOninit lifecycle hook of this component, my browser gets stuck and the component doesn't load properly. I've attempted using both lazyloaded and eager loaded components, but ...

Exploring the Validation of Forms in Angular for Practical Implementations

I'm curious to know whether creating a simple form validation process can really be as complicated as it seems, or if I may be overlooking something. It's fairly straightforward to demonstrate the power of form validation in a tutorial setting. ...

What is the process for retrieving the parent component from projected content?

One interesting aspect to explore is the varying behaviors of input based on its 'parent' element. The structure I am referring to is as follows: In my first example, the input is nested within the app-chip-list component. APP COMPONENT HTML & ...