离子3:如何使复选框的行为像单选按钮

时间:2019-04-03 11:32:42

标签: ionic-framework ionic3

我有一个复选框列表,我想使它们的行为类似于单选按钮 我该怎么办?

我尝试使用单选按钮,但是我没有得到用户输入的值,所以我放弃了单选按钮的想法,并实现了复选框,在该选项中我获得了正确的值,并且除选择多个复选框外,其他所有内容都很完美,我想删除该

这是我的代码:

selectOption(name, isChecked) {
    if (isChecked === true) {
      this.selectednames.push(name);
    } else {
      let index = this.removeCheckedFromName(name);
      this.selectednames.splice(index, 1);
    }
  }
  removeCheckedFromName(names: String) {
    return this.selectednames.findIndex((ref) => {
      return ref === names;
    });
  }

使用我的HTML

<ion-list>
      <ion-list-header>
        Choose Your Team
      </ion-list-header>

      <ion-item *ngFor="let names of name; let i = index">
        <ion-label>{{name}}</ion-label>
        <ion-checkbox item-left color="secondary" formControlName="name"
          (ionChange)="selectOption(name, $event.checked)">
        </ion-checkbox>
      </ion-item>
    </ion-list>

任何建议都受到高度赞赏

2 个答案:

答案 0 :(得分:1)

checkbox-stovr.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>checkbox-stovr</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-list-header>
      Choose Your Team
    </ion-list-header>

    <ion-item *ngFor="let name of names; let i = index">
      <ion-label>{{ name['name'] }}</ion-label>
      <ion-checkbox [(ngModel)]="name['isChecked']" (click)="toggle(name)">
      </ion-checkbox>
    </ion-item>
  </ion-list>
</ion-content>

CheckboxStovrPage

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-checkbox-stovr',
  templateUrl: './checkbox-stovr.page.html',
  styleUrls: ['./checkbox-stovr.page.scss'],
})
export class CheckboxStovrPage implements OnInit {


  names = [{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd' },];
  public selected: string;
  constructor() { }

  ngOnInit() {
  }

  public toggle(selected) {
    for (let index = 0; index < this.names.length; index++) {
      if (this.names['name'] != selected['name'])
        this.names[index]['isChecked'] = null;
    }
  }



}

答案 1 :(得分:0)

您是否一次只选择一个值?