Harsh Maisheri
Harsh Maisheri

Reputation: 149

Ionic 3 : How to make checkboxes behavior like radio-button

I have a list of checkboxes and I want to make them behave like radio button How can I do this?

I tried using radio button but I am not getting the value of the user input so I dropped the idea of radio button and implement checkbox where i get the proper value & everything is perfect except the multiple checkbox selection I want to remove that

Here is my code:

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;
    });
  }

in my 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>

Any advices is highly appreciated

Upvotes: 1

Views: 2604

Answers (1)

Sri Vivek
Sri Vivek

Reputation: 535

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;
    }
  }



}

Upvotes: 2

Related Questions