'Click on ion-label to toggle the ion-toggle

I am creating a page with ionic 5.

I am making a 'remember me' button with use of <ion-toggle>.

<ion-item>
    <ion-label>remember me</ion-label>
    <ion-toggle class="button"></ion-toggle>
</ion-item>

The Ion-toggle is working fine, but I can't toggle it by clicking on the label next to it.

I have tried many solutions.

The link for the API documentation is: https://ionicframework.com/docs/api/toggle

Is there any way to make both the ion toggle and the text clickable?

I'm using ionic angular

Thanks in advance



Solution 1:[1]

In ts file : Declare:

@ViewChild('mytoggle', {static: true}) mytoggle: IonToggle;

changeToggle() {
    const toggle = this.mytoggle.checked;
    toggle = !toggle;
}

In html :

 <ion-item>
            <ion-label (click)="changeToggle()">remember me</ion-label>
            <ion-toggle class="button">
   </ion-toggle>
          </ion-item>

Solution 2:[2]

Hi, the solution for everything will be:

<ion-toggle color="danger" [(ngModel)]="myvar" [checked]="myvar" (ionChange)=myMethod()></ion-toggle>

Inside your component:

myMethod() {
    console.log(">>>>: " + this.myvar);
    if (this.myvar) {
      //do something
    } else {
      //do something
    } 
  }

Hope this solve every question.

Solution 3:[3]

The Solutions above only working with one toggle. If you have a dynamic From, you need the following:

TS File:

changeToggle(fieldname) {
    const fieldValue = JSON.parse(this.form.get(fieldname).value);
    this.form.controls[fieldname].setValue(!fieldValue);
}

HTML File:

<ion-label (click)="changeToggle(item.name)">{{item.label}}:</ion-label>
    <ion-toggle formControlName="{{item.name}}"
                (ionChange)="settingsChange($event)">
</ion-toggle>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomas Vancoillie
Solution 2 Jairdean
Solution 3 hydrococcus