2

I have few checkboxes,whose Value is coming from loop,Here my requirement is only onload all checkbox will be checked by default,but on click clear button all checkbox should be unchecked,Here is the code below

home.component.html

<li *ngFor="let child of nestedjson; let i = index"><input type="checkbox" checked>{{child.name}}</li>
<div><button (click)="clear()" type="submit">clear</button></div>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import Speech from 'speak-tts';
import { RxSpeechRecognitionService, resultList, } from '@kamiazya/ngx-speech-recognition';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],

  providers: [ RxSpeechRecognitionService ]
})
export class HomeComponent implements OnInit {  
    showit:any;
    nestedjson:any;
 constructor(private formBuilder: FormBuilder,public service: RxSpeechRecognitionService) {
     }

  ngOnInit() {
       this.nestedjson = [
        { name: "parent1", value: ["child11", "child12"] },
        { name: "parent2", value: ["child2"] },
        { name: "parent3", value: ["child3"] }
      ];
      this.showit = true;

} 

clear(){

}

}
1
  • Have you tried the modified solution? Commented Nov 9, 2019 at 19:37

1 Answer 1

2

Try like this:

Working Demo

.html

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

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

.ts:

nestedjson = [
    { name: "parent1", value: ["child11", "child12"], checked: true },
    { name: "parent2", value: ["child2"], checked: true },
    { name: "parent3", value: ["child3"], checked: true }
  ];

  clear() {
    this.nestedjson.forEach(child => {
      child.checked = false
    })
  }

If you cannot change the json, do this:

.ts

checkedItems = this.nestedjson.map(x => ({ name: x.name, checked: true }));

.html

<li *ngFor="let child of nestedjson; let i = index">
  <input type="checkbox" [(ngModel)]="checkedItems[i].checked">
  {{child.name}}
</li>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer,We cannot change json here,we cannot add 'checked: true' inside json
This is the ‘correct’ approach though. Why can’t you add the checked keys? They don’t have to exist in the ‘original’ json, but you can make a copy maybe?
Check the modified demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.