简体   繁体   English

只允许选中一个复选框并获取选中的值

[英]Allow check only one checkbox and get value of checked

I got at this moment only 2 checkboxes, what I want to achieve?我此时只有2个复选框,我想要实现什么? If you check checkbox for example - value 2 ( but you previously checked value 1 ) I want to uncheck value1 and select only value2.例如,如果您选中复选框 - 值 2(但您之前选中了值 1),我想取消选中 value1 和 select 仅 value2。 And if you want to select again value1 then uncheck value2.如果你想再次 select value1 然后取消选中 value2。

I prepared stackblitz for my issue https://stackblitz.com/edit/angular-pr9rf3?file=src/app/app.component.ts我为我的问题https://stackblitz.com/edit/angular-pr9rf3?file=src/app/app.component.ts 准备了 stackblitz

I want to allow select only one checkbox then disable second but I want also to uncheck this so I can again select checkbox.我想只允许 select 一个复选框,然后禁用第二个,但我也想取消选中这个,所以我可以再次 select 复选框。

Here is the code: app.component.ts这是代码: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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