I have a toggle button. When it is ONLY checked, I want to call a function. The problem is it is also called when I uncheck it. How can I fix that?
<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>
function in .ts file:
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));
});
}
ion-toggle
has only ionChange
method which fires when the toggle is changed whether it's checked or unchecked. What you can do is check inside your function if it's checked or uncheck and then process your rest of the code.
You have binded the toggle with isActive
and you can use it like:
getGeoLocation(event) {
if (isActive) {
// rest of your code
}
}