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

Having difficulty sending emails with attachments using AngularJS

While using Angular, I encountered an issue when sending an email with an attachment. The response I received contained the data code of the file instead of its actual format. See example: https://i.stack.imgur.com/vk7X8.png I am unsure what is causing t ...

Resetting and marking an Angular2 form as untouched

Is it possible to reset a form and mark it as untouched, clean, etc after submission while staying on the page to avoid resubmission? this.myForm.reset() this.myForm.markAsPristine() this.myForm.controls['options_name'].markAsUntouch ...

Send information to Angular's Google chart module

Currently, I am working with Google Charts in Angular 7 and have a specific requirement to dynamically pass the reportData into the drawChart function. var reportData = {"High":100, "Medium" : 200, "Low" : 300} generateChart() { setTimeo ...

Error: The variable _ is undefined when trying to use the .map() function on an array

While working on my project, I encountered a "ReferenceError: _ is not defined" when using the .map function in this code snippet: arr.map(async (elem) => { ... }); I couldn't find any explicit mention of "_" in my code. The error trace pointed me ...

Is TypeScript being converted to JavaScript with both files in the same directory?

As I begin my journey with TypeScript in my new Angular project, I find myself pondering the best approach for organizing all these JS and TS files. Currently, it appears that the transpiler is placing the .js files in the same directory as the correspondi ...

Is it planned to include StencilJS as a development choice in Ionic?

I'm curious about the potential adoption of Stencil JS for developing mobile apps within the Ionic framework. When I mention "an option for developing," I'm referring to frameworks like NativeScript where developers can choose between Angular + ...

Ensure that the key and value types in a Typescript Map are strictly specified

Is it feasible to generate a map that consists of key-value pairs, where the key is represented by a string and the value corresponds to an object containing specific properties defined by mapValue? type mapValue { first: string; second: boolean; } Yo ...

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

Leveraging Angular2 for Azure AD authentication

Currently working with Angular2 and looking to authenticate users through Azure AD. I came across ADALjs, but it's specifically for Angular1. I also found this https://www.npmjs.com/package/angular2-adal#adalService, however it appears to still be in ...

Utilizing the WebSocket readyState to showcase the connection status on the application header

I am currently in the process of developing a chat widget with svelte. I aim to indicate whether the websocket is connected or not by utilizing the websocket.readyState property, which has the following values: 0- Connecting, 1- Open, 2- Closing, 3- Close ...

Is it possible to integrate ngx-translate with database-supported translations?

I am managing a vast database (pouchDB) that stores translations, with each language having its own dedicated database. How can I leverage ngx-translate to easily access these translations directly from the database? ...

What is the procedure for linking the value (<p>John</p>) to the mat form field input so that it displays as "John"?

Can I apply innerHTML to the value received from the backend and connect it to the matInput? Is this a viable option? ...

Semantic-ui-react cannot be located by Docker

I am a beginner when it comes to docker and I'm looking to create a React app, specifically using TypeScript, inside a docker container. In order to do this, I need to incorporate semantic-ui-react into my project. I followed the instructions provide ...

Converting <reference path/> directive to ESM import: A step-by-step guide

As I embark on developing a TypeScript application, I've reached the realization that I am not a fan of using the <reference path /> triple-slash directive. Instead, I prefer utilizing import 'something'. However, every time I attempt ...

Troubleshooting TypeScript: Issues with Object.assign and inheritance

After successfully using the code within an Angular project, I decided to switch to React only to find that the code is now producing unexpected results. class A { constructor(...parts: Partial<A>[]) { Object.assign(this, ...parts); } } cla ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

What is the best way to eliminate any extra spaces from a string using typescript?

Currently in my Angular 5 project, I am encountering an issue with using the .trim() function in TypeScript on a string. Despite implementing it as shown below, no whitespace is being removed and also there are no error messages appearing: this.maintabinf ...

How to access a static TypeScript variable in Node.js across different files

I encountered a situation like this while working on a node.js project: code-example.ts export class CodeExample { private static example: string = 'hello'; public static initialize() { CodeExample.example = 'modified'; } ...

Tips for obtaining the Component instance from the ViewContainerRef.get() method for dynamically created components

Explanation of my current goal successfully add components to a ViewContainerRef (completed) initialize these dynamic components with properties (done) gain access to the dynamically created Component instances for decision-making purposes. The issue at ...

Can you explain the concepts of observables, observers, and subscriptions in Angular?

As I dive into Angular, I find myself tangled in the concepts of observables, observers, and subscriptions. Could you shed some light on these for me? ...