为什么我取消切换按钮后仍会触发切换按钮功能?

问题描述 投票:0回答:2

我有一个切换按钮。当仅选中它时,我想调用一个函数。问题是,当我取消选中它时也会调用它。我该如何解决?

    <ion-grid class="geoGrid">
          <ion-row justify-content-center align-items-center>
            <ion-col>
              <ion-label position="stacked" class="geoLabel"
                >Use current location</ion-label
              >
            </ion-col>
            <ion-col class="geoToggle">
              <ion-item lines="none">
                <ion-toggle
                  slot="start"
                  name="blueberry"
                  [(ngModel)]="isActive"
                  (ionChange)="getGeoLocation($event)"
                ></ion-toggle>
              </ion-item>
            </ion-col>
          </ion-row>
        </ion-grid>

。ts文件中的功能:

      getGeoLocation(event) {
        console.log(event.detail.checked);
        this.geolocation.getCurrentPosition({ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }).then((resp: any) => {
          this.locationPermissionsDenied = false;
          this.geoLatitude = resp.coords.latitude;
          this.geoLongitude = resp.coords.longitude;
          const city = {
            isActive: this.isActive,
            latitude: this.geoLatitude,
            longitude: this.geoLongitude
          };
          console.log(this.isActive);
          this.httpService.changeIsActive(this.isActive);
          this.httpService.changeCity(city);
        }).catch((error) => {
          alert('Error getting location ' + JSON.stringify(error));
        });
      }
angular ionic-framework ionic4 angular-ngmodel
2个回答
0
投票

您只需要一些逻辑即可查看是否已选中该框:

getGeoLocation(event) {
        console.log(event.detail.checked);
        if(event.detail.checked) {
            this.geolocation.getCurrentPosition({ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }).then((resp: any) => {
            this.locationPermissionsDenied = false;
            this.geoLatitude = resp.coords.latitude;
            this.geoLongitude = resp.coords.longitude;
            const city = {
              isActive: this.isActive,
              latitude: this.geoLatitude,
              longitude: this.geoLongitude
            };
            console.log(this.isActive);
            this.httpService.changeIsActive(this.isActive);
            this.httpService.changeCity(city);
          }).catch((error) => {
            alert('Error getting location ' + JSON.stringify(error));
          });
       }
 }

0
投票

ion-toggle仅具有ionChange方法,该方法在更改切换(无论已选中还是未选中)时都会触发。您可以做的是检查函数内部是否被选中或取消选中,然后处理其余代码。

您已将切换开关与isActive绑定在一起,可以像这样使用它:

getGeoLocation(event) {
  if (isActive) {
    // rest of your code
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.