简体   繁体   中英

How to make a checkbox checked based on its parent div clicked inside ngFor?

I have a list of checkboxes inside ngFor. Each checkbox has its own parent div. I want checkboxes to be checked once the div clicked.

Here is my code.

<div *ngFor="let option of qustions; let i = index" (click)="doCheckboxCheck()">
  <input type="checkbox" [value]="option.value">
  <span>Checkbox {{i}}</span>
</div>

You could assign an Angular template reference variable to the <input> element and toggle it's checked property in the <div> 's click or mouseup event.

Now this could modify the default behavior of checkbox's own click event, so you could bind the [checked] toggle to <input> too.

<div 
  class="checkbox-container" 
  *ngFor="let option of questions; let i = index"
  (mouseup)="inputCheckbox.checked = !inputCheckbox.checked"
>
  <input
    #inputCheckbox
    class="checkbox"
    type="checkbox"
    [value]="option.value"
    (mouseup)="inputCheckbox.checked = !inputCheckbox.checked"
  >
  <span>Checkbox {{ option.value }}</span>
</div>

Working example: Stackblitz

We can change the state of the checkbox on div click by passing the index to the even handler. Please refer to the link below which is having a working solution,

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  questions = [
    { value: "Checkbox-1", checked: false },
    { value: "Checkbox-2", checked: false },
    { value: "Checkbox-3", checked: false },
    { value: "Checkbox-4", checked: false },
    { value: "Checkbox-5", checked: false }
  ];

  doCheckboxCheck(index: number): void {
     this.questions[index].checked = !this.questions[index].checked;
  }
}

Template:

<div *ngFor="let option of questions; let i = index" (click)="doCheckboxCheck(i)">
  <input type="checkbox" [value]="option.value" [checked]="option.checked">
  <span>Checkbox {{i}}</span>
</div>

editor url - https://stackblitz.com/edit/checkbox-click?file=src/app/app.component.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM