ionic2

Ionic 2/3 : How to programmatically uncheck a check box


I have a situation wherein I have to uncheck a checkbox, onclick of a button.

This is my checkbox code

<ion-checkbox [checked]="!isChecked" [disabled]="!isdisabled" (ionChange)="saveProfile($event)" [(ngModel)]="default"></ion-checkbox>

I have tried using !iChecked, but it doesn't work. Basically, if the checkbox is already checked by the user, I want it to be unchecked (based on certain conditions) when you click a button.

<button class="button-m" (click)="navigateTo()" ion-button color="secondary"><ion-icon name="next">&nbsp;&nbsp;</ion-icon> Next </button>

TS file

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ToastController } from 'ionic-angular';

@Component({
  selector: 'choose-profile',
  templateUrl: 'choose-profile.html',
})
export class ChooseProfilePage {
  profileValue : string;
  isdisabled : boolean;
  isChecked :boolean;
  constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController) {

  } 
  getSelectedProfile(val){
    this.profileValue = val;

    if(this.profileValue!=undefined){
       this.isdisabled = true;
    }
    else{
      this.isdisabled = false;
    }
  }
  saveProfile(val){
    if(val.checked==true)
    {
     this.presentToast( this.profileValue+"set as default profile")
    }
    else
    {
      this.presentToast("No default profile")
    }
  }

  presentToast(val){
    let toast = this.toastCtrl.create({
      message: val,
      duration: 3000,
      position: 'top'
    });
    toast.present();
  }

  navigateTo()
  {
    console.log("Next Clicked")
    this.isChecked == true;
  }


}

Solution

  • You have an error in your code. this.isChecked == true; does not set the isChecked variable to true. It merely does a comparison to check if isChecked is true. You should use = instead of ==.

    Alter your code to be as following:

      navigateTo()
      {
        console.log("Next Clicked")
        this.isChecked = true;
      }