单击离子标签以切换离子切换

Click on ion-label to toggle the ion-toggle

我正在使用 ionic 5 创建页面。

我正在使用 <ion-toggle> 制作一个 'remember me' 按钮。

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

Ion-toggle 工作正常,但我无法通过单击它旁边的标签来切换它。

我尝试了很多解决方案。

API 文档的 link 是:https://ionicframework.com/docs/api/toggle

有什么方法可以让离子切换和文本都可以点击吗?

我正在使用离子 angular

提前致谢

在 ts 文件中: 声明:

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

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

在html中:

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

你可以这样做:

  • 将 Ionic id 添加到开关中,例如 #mytoggle
  • 使用标签(click)中的id来切换.checked属性

代码:

<ion-item>
    <ion-label (click)="mytoggle.checked = !mytoggle.checked">remember me</ion-label>
    <ion-toggle #mytoggle class="button"></ion-toggle>
</ion-item>

Try it in stackblitz

以上解决方案仅适用于一个切换。如果您有动态发件人,则需要以下内容:

TS 文件:

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

HTML 文件:

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

您好,所有问题的解决方案都是:

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

在您的组件内:

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

希望这能解决所有问题。