The Step-by-Step Guide to Deselecting an Angular Checkbox with a Button

I currently have a situation where I have three checkboxes labeled as parent 1, parent 2, and parent 3. Initially, when the page loads, parent 1 and parent 3 are checked by default, while parent 2 is unchecked. However, when I manually check parent 2 and click on the clear button, only the checkboxes that were initially checked (parent 1 and parent 3) get unchecked, while parent 2 remains checked. Here is the code snippet related to this:

         <li *ngFor="let child of nestedjson; let i = index">
            <input type="checkbox" [checked]="child.checked">
             {{child.name}}
         </li>

        <div><button (click)="clear()" type="submit">clear</button></div> 

In the TypeScript file:

  nestedjson = [
             { name: 'parent1', value: ['child11', 'child12'], checked: true },
             { name: 'parent2', value: ['child2'], checked: false },
             { name: 'parent3', value: ['child3'], checked: true },
               ];
                      
    clear() {
          this.nestedjson.forEach((child) => {
              child.checked = false;
                });
             }

Answer №1

Updating the value in HTML is essential to ensure that Angular recognizes any changes made to the checkbox value.

The code snippet below demonstrates how the value can be updated:

// Import required libraries
import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';

// Define and configure the component
@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule],
  template: `
  <li *ngFor="let child of nestedjson; let i = index">
    <input type="checkbox" [checked]="child.checked" (change)="child.checked = true"> <!-- Value update applied here -->
    {{child.name}}
  </li>

  <div>
    <button (click)="clear()" type="submit">Clear</button>
  </div> 
  `,
})
export class App {
  nestedjson = [
    { name: 'parent1', value: ['child11', 'child12'], checked: true },
    { name: 'parent2', value: ['child2'], checked: false },
    { name: 'parent3', value: ['child3'], checked: true },
  ];

  // Function to clear all checkboxes
  clear() {
    this.nestedjson.forEach((child) => {
      child.checked = false;
    });
  }
}

// Bootstrap the application
bootstrapApplication(App);

For a working example, you can visit the following StackBlitz link.

Answer №2

Use the change event to ensure that the item in the list is constantly updated.

<input type="checkbox" [checked]="item.checked" (change)="item.checked = $event.target.checked">

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

Is there a way to dynamically update the text of $ionicPopup's subTitle in Ionic?

I am currently attempting to modify both the value and style of the subText attribute linked to an $ionicPopup within my app. Despite searching extensively, I have been unable to uncover a viable method for accomplishing this task. Is there a way to achi ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Alignment of content layout across two wrapper elements

My goal is to achieve a specific layout where each pair of cards in a two-column layout is aligned based on the card with the largest content. Both cards share the same content layout and CSS. If you have any ideas or implementations that could help me ac ...

An effective way to determine the size of a browser through javascript

In an effort to enhance the responsiveness of a website, I have included the following code snippet on one of my pages: document.write(screen.width+'x'+screen.height); However, I am encountering an issue where the code displays my screen resolu ...

What is causing my fetch response to not be passed through my dispatch function?

I'm currently utilizing a node server to act as the middleman between firebase and my react native app. Could someone kindly point out what might be going awry in my fetch method below? export const fetchPostsByNewest = () => { return (dispatch ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

After updating to version 13 of Angular and Angular Material, the mat-contenteditable feature has ceased functioning

Encountered errors with mat-contenteditable after updating Angular from version 12 to 13 Error: /node_modules/mat-contenteditable/lib/mat-ckeditor.directive.d.ts:9:22 - error TS2420: Class 'MatCkeditorDirective' incorrectly implements interface & ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Adding a data attribute to a group of elements derived from an array

Looking to enhance the functionality of a slick slider by creating a custom navigation with buttons that will work alongside the original navigation dots. To achieve this, I need to extract the 'data-slick-index' attribute from every fourth slid ...

Show a loading icon as the synchronous Ajax request is being sent

Seeking a way to show a spinner while making a synchronous Ajax request to fetch data from the server. Acknowledging that asynchronous mode is preferred, but not permitted in this case. Aware that a sync ajax request can cause browser blocking. An attemp ...

When using React.js, clicking on an answer option will change the color of all options, not just the one that was clicked

I'm currently working on my quiz page where all answer options change color when clicked. However, I only want the selected answer option to be colored based on its correctness. The data is being retrieved from a data.json array. export default functi ...

Creating a responsive DataTable filled from a $.ajax request is a straightforward process that can greatly

I am in the process of creating an application that retrieves a lot of data from a web-service query and populates a data table with it. The data shows up correctly and styled properly on desktop, but when I switch to viewing it on a mobile device, the dat ...

An application running on Node.js/Express and hosted on Digital Ocean encounters the "Cannot get /" error message

Despite searching extensively online and sifting through numerous solutions to different scenarios, I remained unable to find a fix that resolved my issue. When attempting to run my server.js file locally, everything operates smoothly. However, upon transf ...

Creating a mandatory 'Select' component in Material UI with React JS

Is there a method to show an error message in red until a choice is selected? ...

Production environment experiences issues with Angular animations

In my MEAN stack application, I started with Sails.js. Everything was working smoothly during development, especially with angular-animate. However, once I changed the Sails environment to production, I encountered issues. Grunt is set up to concatenate a ...

Printing Apex Oracle reports using Internet Explorer

I am facing a challenge with printing my page that contains two interactive reports. To enable printing, I have utilized a JavaScript function that triggers window.print(). I have incorporated CSS to adjust the layout of my tables when printed. @media pr ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...

jQuery form validation not functioning as expected

I'm attempting jQuery form validation but encountering issues with the desired functionality. I would like the border of an input to turn red when it's empty upon focus out. Alternatively, I aim to incorporate the "has-danger" bootstrap class to ...

Running a JavaScript function within a designated div element

I'm currently facing an issue with executing a javascript function - onload only in a specific div. I seem to be stuck on this problem, so if anyone could offer some assistance, I would greatly appreciate it. Thank you very much in advance! functio ...