【问题标题】:I want user to select only one checkbox instead of multiple? How can I approach in angular?我希望用户只选择一个复选框而不是多个?我怎样才能以角度接近?
【发布时间】:2021-11-08 13:16:18
【问题描述】:

我有多个复选框,但我希望用户选择一个复选框而不是多个复选框,如果他选中一个复选框并返回选中值,否则什么都不会显示。有人可以帮忙吗?

<div class="form-check" *ngFor="let product of DisplayProductList">
    <label class="form-check-label text-break">
        <input class="form-check-input" type="checkbox" [value]="true" [(ngModel)]="product.isChecked"
            (change)="changeSelection($event)" />
        {{ product.template_name }}
        <span class="form-check-sign">
            <span class="check"></span>
        </span>
    </label>
</div>
changeSelection(event: any) {
  this.checkedIDs = [];
  if (event.target.checked) {
    this.selectedItemsList = this.DisplayProductList.filter(
      (product, index) => {
        if (product.isChecked == true) {
          let splitstring = product.template_parameter;
          let sepratedArray = splitstring.split(',');
          this.variable1 = sepratedArray[0];
          this.variable2 = sepratedArray[1];
          this.checkedIDs.push(product.id);

          this.sendclusteridApi(this.productid);
          return product.isChecked;
        }
      }
    );
  }
}

【问题讨论】:

  • 通常,这就是单选按钮的用途。
  • 是的,我们可以为复选框做到这一点。
  • 为什么不使用单选按钮?有什么特别的原因吗?

标签: angular checkbox


【解决方案1】:

正如 cmets 中提到的,这就是单选按钮的作用,但如果您需要使用复选框实现相同的功能,您可以通过以下方式实现:

  • 定义一个selectedIndex 变量,并为其分配最后一个选中复选框的索引。
  • 将复选框的ngModel 绑定到[ngModel]="selectedIndex === index",其中index 是*ngFor 循环中复选框的索引。
<div class="form-check" *ngFor="let product of DisplayProductList; let index = index">
  <label class="form-check-label text-break">
    <input class="form-check-input" type="checkbox" [ngModel]="selectedIndex === index"
        (change)="changeSelection($event, index)" />
    {{ product.template_name }}
    <span class="form-check-sign">
        <span class="check"></span>
    </span>
</label>
</div>
selectedIndex: number;

changeSelection(event, index) {
  this.selectedIndex = event.target.checked ? index : undefined;

  // do your logic here...
}

【讨论】:

  • 非常感谢 Amer。我已经添加了你的代码,它按预期工作但没有返回我的检查值,在下面添加了代码,我的逻辑有什么问题吗?
  • changeSelection(event,index) { this.selectedIndex = event.target.checked ?索引:未定义; if (event.target.checked) { this.selectedItemsList = this.DisplayProductList.filter((product, index) => { if (product.isChecked == true) { let splitstring = product.template_parameter let sepratedArray = splitstring.split( ','); this.variable1 = sepratedArray[0]; this.variable2 = sepratedArray[1]; return product.isChecked } } ); } 其他 { }
  • 请问您需要在哪里准确返回/存储检查的值?
  • 当复选框被选中时,我想返回,
  • 我知道,但是您要为其分配检查值的变量是什么?
猜你喜欢
  • 2021-11-24
  • 2016-04-04
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多