skip to Main Content

I have three check boxes (parent 1, parent 2, parent 3) and in those three two by default checked (parent 1, parent 3)and one unchecked (parent 2) and when I checked the unchecked checkbox (parent 2) and click on clear button only those by default check boxes are unchecking(parent 1, parent 3) other one is remaining checked. here is the code :

         <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 ts

  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;
                });
             }

2

Answers


  1. You need to update the value in html, else angular thinks there is no change to the checkbox value

    Change:

    import 'zone.js/dist/zone';
    import { Component } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { bootstrapApplication } from '@angular/platform-browser';
    
    @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"> <!-- changed 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 },
      ];
    
      clear() {
        this.nestedjson.forEach((child) => {
          child.checked = false;
        });
      }
    }
    
    bootstrapApplication(App);
    

    stackblitz

    Login or Signup to reply.
  2. Handle the change event to update the object in the array.

    <input type="checkbox" [checked]="child.checked" (change)="child.checked = $event.target.checked">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search