简体   繁体   中英

Allow check only one checkbox and get value of checked

I got at this moment only 2 checkboxes, what I want to achieve? If you check checkbox for example - value 2 ( but you previously checked value 1 ) I want to uncheck value1 and select only value2. And if you want to select again value1 then uncheck value2.

I prepared stackblitz for my issue https://stackblitz.com/edit/angular-pr9rf3?file=src/app/app.component.ts

I want to allow select only one checkbox then disable second but I want also to uncheck this so I can again select checkbox.

Here is the code: app.component.ts

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

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular";
  public checklist: any[];
  constructor() {
    this.checklist = [
      { id: 1, value: "value1", isSelected: false },
      { id: 2, value: "value2", isSelected: false }
    ];
  }

  isAllSelected(item) {
    this.checklist.forEach(val => {
      if (val.id == item.id) val.isSelected = !val.isSelected;
      else {
        val.isSelected = false;
      }
    });
  }
}

app.component.html

<hello name="{{ name }}"></hello>
<div class="col-md-12 align-items-center">
    <ul class="list-group">
        <li class="list-group-item" *ngFor="let item of checklist">
            <input type="checkbox" value="{{item.id}}" [checked]="item.isSelected"
 (change)="isAllSelected(item)"/>
                  {{item.value}}</li>
    </ul>
</div>

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