【问题标题】:Allow check only one checkbox and get value of checked只允许选中一个复选框并获取选中的值
【发布时间】:2021-01-21 12:12:19
【问题描述】:

此时我只有 2 个复选框,我想要实现什么? 例如,如果您选中复选框 - 值 2(但您之前选中了值 1),我想取消选中 value1 并仅选择 value2。如果您想再次选择 value1,请取消选中 value2。

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

我想只允许选择一个复选框,然后禁用第二个,但我还想取消选中它,以便我可以再次选择复选框。

【问题讨论】:

  • 为什么不使用单选按钮?
  • 如果我想更改收音机的类型,我无法获得价值?尝试在堆栈上更改?

标签: angular typescript


【解决方案1】:

代码如下: 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>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 2017-10-04
  • 2016-05-22
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2020-09-09
相关资源
最近更新 更多