---
updatedAt: 2025-07-15T08:30:36.000Z
agentTools:
  projectIndex: https://docs.appery.io/llms.txt
---

# Snippets

Working with code snippets in an Ionic application

# Introduction to Snippets

Some of the predefined events that are available for the **[App Builder](https://docs.appery.io/docs/apperyio-visual-builder)** come with the out-of-the-box snippets that can be used for:

* UI components (under the **[DESIGN](https://docs.appery.io/docs/apperyio-visual-builder#design-panel)** panel): <https://docs.appery.io/docs/snippets#defining-snippets-for-ui-components>;
* Datasources (under the **[DATA](https://docs.appery.io/docs/apperyio-visual-builder#data-panel)** panel): <https://docs.appery.io/docs/snippets#defining-snippets-for-datasources>;
* Functions (under the **[CODE](https://docs.appery.io/docs/apperyio-visual-builder#code-panel)** panel): <https://docs.appery.io/docs/snippets#defining-snippets-for-code-functions>.

> 👍
>
> To get access to [Appery.io](https://appery.io) code snippets, expand the **[EVENTS](https://docs.appery.io/docs/apperyio-visual-builder#events-tab)** tab from the bottom.

The code snippets are blocks of JavaScript code implementing different useful functionality. Using snippets makes writing custom code easier.

# Defining Snippets for UI Components

Open the **[DESIGN](https://docs.appery.io/docs/apperyio-visual-builder#design-panel)** panel and select the UI component to be defined.\
For example, for the **Button1** component ***Click*** event, select the ***[Run TypeScript](https://docs.appery.io/docs/5-event-handling#run-typescript)*** action.\
Now, in the editor window, click **Insert snippet** and select the needed [snippet](https://docs.appery.io/docs/snippets#code-snippets) from the list:

<Image align="center" className="border" border={true} src="https://files.readme.io/c0dbc41-small-2023-05-11_21-10-29.png" />

# Defining Snippets for Datasources

Open the **[DATA](https://docs.appery.io/docs/apperyio-visual-builder#data-panel)** panel, then select the datasource to be defined.\
For example, for the ***loadGoods*** component ***Before send*** event, select the ***[Run TypeScript](https://docs.appery.io/docs/5-event-handling#run-typescript)*** action.\
Now, in the editor window, click **Insert snippet** and select the needed [snippet](https://docs.appery.io/docs/snippets#code-snippets) from the list:

<Image align="center" className="border" border={true} src="https://files.readme.io/e039ab9-small-2023-05-11_21-14-09.png" />

> 📘 Note
>
> The list of snippets is the same for **[DESIGN](https://docs.appery.io/docs/apperyio-visual-builder#design-panel)** and **[DATA](https://docs.appery.io/docs/apperyio-visual-builder#data-panel)** events as well as for the **[CODE](https://docs.appery.io/docs/apperyio-visual-builder#code-panel)** functions.

# Defining Snippets for Code Functions

Open the **[CODE](https://docs.appery.io/docs/apperyio-visual-builder#code-panel)** panel, create a **Method**, and add its argument, if needed.\
From the list of [snippets](https://docs.appery.io/docs/snippets#code-snippets), select the needed one:

<Image align="center" className="border" border={true} src="https://files.readme.io/11ef6cf-small-2023-05-11_21-19-55.png" />

After a snippet is added, edits can be made to the code.

> 👍 Tip!
>
> You are free to use the helper that will assist in adding needed functions:

<Image align="center" className="border" border={true} src="https://files.readme.io/b470b9e-Animation3.gif" />

> 📘 Angular Life Cycle Events
>
> You can also check this guide covering how the page life cycle works in an app built with Ionic and Angular: <https://ionicframework.com/docs/angular/lifecycle>.

Also, you can insert more snippets into the function or replace strings of code.

> 📘 Adding Services into the Code Function by Drag-and-Drop
>
> One more way to implement functionality to your app is to add the needed services into the scope function via drag-and-drop.
>
> Here is how it works:\
> Open the **[CODE](https://docs.appery.io/docs/apperyio-visual-builder#code-panel)** panel and from the list of services on the left, drag the needed service and drop it into the function code window. This will automatically add the code of the service invocation.

# **Code Snippets**

Below is the list of available snippets:

* ***[Navigate to page](https://docs.appery.io/docs/snippets#navigate-to-page)***
* ***[Navigate forward](https://docs.appery.io/docs/snippets#navigate-forward)***
* ***[Navigate back](https://docs.appery.io/docs/snippets#navigate-back)***
* ***[Navigate root](https://docs.appery.io/docs/snippets#navigate-root)***
* ***[Get route parameter](https://docs.appery.io/docs/snippets#get-route-parameter)***
* ***[Get query parameter](https://docs.appery.io/docs/snippets#get-query-parameter)***
* ***[Invoke service](https://docs.appery.io/docs/snippets#invoke-service)***
* ***[Invoke service sync](https://docs.appery.io/docs/snippets#invoke-service-sync)***
* ***[Execute DataService](https://docs.appery.io/docs/snippets#execute-dataservice)***
* ***[Show modal](https://docs.appery.io/docs/snippets#show-modal)***
* ***[Close modal](https://docs.appery.io/docs/snippets#close-modal)***
* ***[Get controller](https://docs.appery.io/docs/snippets#get-controller)***
* ***[Loading present](https://docs.appery.io/docs/snippets#loading-present)***
* ***[Loading dismiss](https://docs.appery.io/docs/snippets#loading-dismiss)***
* ***[Toast present](https://docs.appery.io/docs/snippets#toast-present)***
* ***[Toast dismiss](https://docs.appery.io/docs/snippets#toast-dismiss)***
* ***[i18n set language](https://docs.appery.io/docs/snippets#i18n-set-language)***
* ***[i18n get translation](https://docs.appery.io/docs/snippets#i18n-get-translation)***
* ***[i18n get browser lang](https://docs.appery.io/docs/snippets#i18n-get-browser-lang)***
* ***[Get variable](https://docs.appery.io/docs/snippets#get-variable)***
* ***[Set variable](https://docs.appery.io/docs/snippets#set-variable)***
* ***[Get from storage](https://docs.appery.io/docs/snippets#get-from-storage)***
* ***[Set to storage](https://docs.appery.io/docs/snippets#set-to-storage)***
* ***[Remove from storage](https://docs.appery.io/docs/snippets#remove-from-storage)***
* ***[Preload ionic icons](https://docs.appery.io/docs/snippets#preload-ionic-icons)***
* ***[Preload ionic components](https://docs.appery.io/docs/snippets#preload-ionic-components)***
* ***[Set theme](https://docs.appery.io/docs/snippets#set-theme)***
* ***[Get current theme](https://docs.appery.io/docs/snippets#get-current-theme)***
* ***[Reorder compete](https://docs.appery.io/docs/snippets#reorder-complete)***
* ***[Get autoupdate version](https://docs.appery.io/docs/snippets#get-autoupdate-server-version)***
* ***[Get autoupdate server version](https://docs.appery.io/docs/ionic-5-snippets#get-autoupdate-version)***
* ***[Download latest autoupdate version](https://docs.appery.io/docs/snippets#download-latest-autoupdate-version)***
* ***[Install latest autoupdate version](https://docs.appery.io/docs/snippets#install-latest-autoupdate-version)***
* ***[Alert present](https://docs.appery.io/docs/snippets#alert-present)***

## Navigate to page

This snippet is used for navigation between the application pages. The `routeName` argument is the route name specified on the **[Routing](https://docs.appery.io/docs/4-routing-and-navigation#using-routing)** tab of the **Project** settings.

```javascript Navigate to page
this.Apperyio.navigateTo("routeName"/*, optional, params, here */);
```

Every route is bound to its own page. Several routes can be bound to one page. The number of routes can be used when navigation is defined with parameters or without them depending on different conditions.

### Parameters Sending

Parameters are used when simple data should be passed to the page at navigation through the URL.\
Note that for sending complicated data (e.g. `Objects`) it is better to use alternative ways, for example, variables using the ***[Set variable](https://docs.appery.io/docs/snippets#set-variable)*** snippet before navigation and the ***[Get variable](https://docs.appery.io/docs/snippets#get-variable)*** snippet after navigation.\
Data as parameters are passed as arguments following up the `routeName` argument.

The values of each parameter should be comma-separated.\
Every parameter is set as a JavaScript expression with special syntax depending on the variable type:

| Parameter name | Data type | Value syntax |
| :------------- | :-------- | :----------- |
| `id`           | Number    | `123`        |
| `name`         | String    | `'john'`     |
| `active`       | Boolean   | `true`       |

The order of parameters should be the same as the order specified in the route ***Path***.\
For example, sending the parameters for the route with the `profileId` name and the path `profile/:id/:name/:active`:

```javascript
this.Apperyio.navigateTo('profileId', 123, 'john', true);
```

If the passed parameter is an object, it should be converted to a string.\
For example, sending the parameters for a route with the `profileUser` name and the path `profile/:user`:

```javascript
const params = JSON.stringify({id: 123, name: 'john'}) // "{"id":123,"name":"john"}"
this.Apperyio.navigateTo('profileUser', params);
```

### Parameters Receiving

Every parameter can be received by its name after navigation to a page.\
If the parameter should be written in a variable specified on the **[CODE](https://docs.appery.io/docs/apperyio-visual-builder#code-panel)** panel, you can use the **[Set variable](https://docs.appery.io/docs/5-event-handling#set-variable)** action.\
In other cases, you can use the ***[Get route parameter](https://docs.appery.io/docs/snippets#get-route-parameter)*** snippet.

## Navigate forward

Navigate to page with **forward** direction. You can set `Route params`, `AnimationOptions` and `NavigationExtras`, if needed:

```javascript
this.Apperyio.navigation.forward("routeName"/*,[route, params, here], {NavigationExtras and AnimationOptions} */);
```

## Navigate back

Navigate to page with **back** direction. You can set `Route params`, `AnimationOptions` and `NavigationExtras`, if needed:

```javascript
this.Apperyio.navigation.back("routeName"/*,[route, params, here], {NavigationExtras and AnimationOptions} */);

```

## Navigate root

Navigate to page with **root** direction and set the target page as a **root** page. You can set `Route params`, `AnimationOptions` and `NavigationExtras`, if needed:

```javascript
this.Apperyio.navigation.root("routeName"/*,[route, params, here], {NavigationExtras and AnimationOptions} */);

```

## Get route parameter

This code snippet is used for receiving parameters sent through the URL at navigation:

```javascript Get route parameter
let paramName = this.Apperyio.getRouteParam("paramName");
```

In this case, the `paramName` argument should be replaced with the actual name of the route parameter specified in route ***Path***. For example, receiving parameters for a route with the path `profile/:id/:name/:active`:

```javascript
let id = this.Apperyio.getRouteParam("id");         // "123"
let name = this.Apperyio.getRouteParam("name");     // "john"
let active = this.Apperyio.getRouteParam("active"); // "true"
```

> 📘 Note
>
> Every parameter is converted to a string after it is received.

Convert parameters to the initial data type:

```javascript
let paramId = this.Apperyio.getRouteParam("id");         // "123"
let paramActive = this.Apperyio.getRouteParam("active"); // "true"
let paramUser = this.Apperyio.getRouteParam("user");     // "{"id":123,"name":"john"}"

JSON.parse(paramId)     // 123
JSON.parse(paramActive) // true
JSON.parse(paramUser)   // {id: 123, name: "john"}
```

## Get query parameter

This code snippet is similar to the ***[Get route parameter](https://docs.appery.io/docs/snippets#get-route-parameter)*** snippet but can be used for receiving parameter values from queries. Use this code:

```javascript
let param = this.Apperyio.getQueryParam("paramName");
```

## Invoke service

This snippet allows users to write their own code for receiving data from a server:

```javascript Invoke service
this.Apperyio.getService("service_name").then(
    service => {
        if (!service) {
            console.log("Error. Service was not found.");
            return;
        }
        service.execute({
            data: {},
            params: {},
            headers: {}
        }).subscribe(
            (res: any) => {
                /* success */
                console.log(res);
            },
            (err: any) => {
                /* error */
                console.log(err)
            }
        )
    }
)
```

In the code above, the `service_name` is not the datasource name but the actual service name (e.g. `app_login_service`).

After the service is run and completed it returns the **success** or **error** result.\
The result of the service is stored in the variable `res` or `err`.\
The received result can be processed by some custom code added to the particular part of the snippet.\
The sent request data can be passed by the `data`, `params`, or `headers` option of the snippet.\
For example, add a code for navigation to a profile page after a user is logged in:

```javascript
this.Apperyio.getService("app_login_service").then(
    service => {
        if (!service) {
            console.log("Error. Service was not found.");
            return;
        }
        service.execute({
            data: {
                username: "user",
                password: "pass"
            },
            params: {},
            headers: {}
        }).subscribe(
            (res: any) => {
                /* success */

                // get user id from server response
                const userId = res["_id"];

                // navigate to the profile page of the logged in user
                this.Apperyio.navigateTo("profile", userId);
            },
            (err: any) => {
                /* error */

                // navigate to the error page if something went wrong
                this.Apperyio.navigateTo("errorPage");
                console.log(err);
            }
        )
    }
)
```

## Invoke service sync

This snippet allows users to write their own code for receiving data from a server.\
The working of the snippet is similar to that of the ***[Invoke service](https://docs.appery.io/docs/snippets#invoke-service)*** snippet. The difference is that the following code allows writing more sequential and readable code:

```javascript Invoke service sync
var service = await this.Apperyio.getService("service_name");
if (service) {
     try {
        var result = await service.execute({
            data: {},
            params: {},
            headers: {}
        }).toPromise();
    } catch (e) {
        /* error */
        console.log('error', e)
    }
} else {
    console.log("Error. Service was not found.");
}
/* success */
console.log(result);

/* following code */
```

In the code above, the `service_name` is not a datasource name but the actual service name (e.g. `users_login_service`).

After the service is run and completed it returns the **success** or **error** result. The result of the service is stored in a variable `result` or `e`.\
The received result can be processed by some custom code written in a particular part of the snippet.\
The sent request data can be passed by the `data`, `params`, or `headers` option of the snippet.\
For example, write a code for navigation to a profile page after a user is logged in:

```javascript
var service = await this.Apperyio.getService("app_login_service");
if (service) {
     try {
        var result = await service.execute({
            data: {
                username: "user",
                password: "pass"
            },
            params: {},
            headers: {}
        }).toPromise();
    } catch (e) {
        /* error */
        
        // navigate to the error page if something went wrong
        this.Apperyio.navigateTo("errorPage");
        console.log('error', e)
    }
} else {
    console.log("Error. Service was not found.");
}
/* success */

// check if the result exists
if (result) {
  // get user id from server response
  const userId = result["_id"];

  // navigate to the profile page of the logged in user
  this.Apperyio.navigateTo("profile", userId);
}

/* following code */
```

## Execute DataService

This snippet executes a datasource service added in the **[DATA](https://docs.appery.io/docs/apperyio-visual-builder#data-panel)** panel:

```javascript Execute DataService
this.Apperyio.execDataService(this, "service_name");
```

In the code above, the `service_name` argument should be replaced with the actual datasource name:

```javascript
this.Apperyio.execDataService(this, "service1");
```

## Show modal

This snippet opens a modal page:

```javascript Show modal
this.Apperyio.showModal("screenName", {
    componentProps: {},
    showBackdrop: true,
    backdropDismiss: true,
    cssClass: "",
    animated: true,
    keyboardClose: true
})
.then(modal => {
    modal.present();
    modal.onDidDismiss().then((dataReturned) => {
        // console.log(dataReturned.data);
    });
});
```

In the code above, the `screenName` argument should be replaced with the actual modal page name.\
To set the page as a modal, define its **Modal Screen** property as ***True***.

> 📘 Info
>
> Modal pages are based on the Ionic [Modal](https://ionicframework.com/docs/api/modal) component.

### Options

The following options allow customizing the shown modal:

* `animated` - if set to ***true***, the modal will animate;
* `backdropDismiss` - if set to ***true***, the modal will be dismissed when the backdrop is clicked;
* `componentProps` - data to pass to the modal component;
* `cssClass` - additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces;
* `keyboardClose` - if set to ***true***, the keyboard will be automatically dismissed when the overlay is presented;
* `showBackdrop`- if set to ***true***, a backdrop will be displayed behind the modal.

<Image align="center" className="border" border={true} src="https://files.readme.io/3e664fe-ShowModalOptions.jpg" />

Two more options can be added manually:

* `mode` - determines which platform styles to use (***ios*** or ***md***);
* `swipeToClose` - if set to ***true***, the modal can be swiped to dismiss. This only applies in the ***iOS*** mode.\
  Note that if the modal page has been added by using the [**Open modal page**](https://docs.appery.io/docs/events-and-actions#open-modal-page) action, these options become available for editing by default:

<Image align="center" className="border" border={true} src="https://files.readme.io/adfbdf7-Open_modal_page.jpg" />

### Sending Data to a Modal Page

The `componentProps` is used for sending data to a modal page.\
The option receives an object of data:

```javascript
{
  componentProps: {
    name: 'john',
    age: 21
  }
}
```

To make data available on the modal page, it should be specified as variables on the **[CODE](https://docs.appery.io/docs/apperyio-visual-builder#code-panel)** panel of the opened modal page.\
The names of the created variables, in this case, should fully correspond with the actual names in the sent data object (e.g. `name` or `age`).\
After the definition, the variables are available as:

```javascript
this.name // 'john'
this.age  // 21
```

### Receiving Data from a Modal Page

The data received from a modal page after its closing is available as a variable inside the `onDidDismiss` handler function specified at showing the modal page.\
In the code above, such a variable has the name of `dataReturned`.\
The variable contains an object with the `data` property that includes the data received from the modal page.\
To close modal pages and send data from them, use the ***[Close modal](https://docs.appery.io/docs/snippets#close-modal)*** snippet.\
To have the possibility of controlling the modal, use the `ModalController` controller received with the ***[Get controller](https://docs.appery.io/docs/snippets#get-controller)*** snippet.

## Close modal

This snippet closes the opened modal page.

```javascript Close modal
this.Apperyio.getController("ModalController").dismiss(/* data */);
```

To send data from a closed modal, pass data as an argument of the `dismiss` method of the snippet:

```javascript
this.Apperyio.getController("ModalController").dismiss({
    name: 'john',
    age: 21
});
```

The sent data will be received in the `onDidDismiss` handler function specified at showing the modal page.\
Receiving data from a modal page is described in the section [Show modal](https://docs.appery.io/docs/snippets#show-modal).

> 📘 Want to know more?
>
> You can check [this](https://docs.appery.io/docs/ionic-5-solutions#passing-data-tofrom-modal-screen) document to learn how to pass properties from a screen to a modal screen and back by using the corresponding snippets.

## Get controller

This snippet gets a controller that allows applying special functionality to different components:

```javascript Get controller
let controller = this.Apperyio.getController("ControllerName");
```

In the code above, the `ControllerName` argument should be replaced with one of the controller's names.

Available controllers are:

* [`ActionSheetController`](https://docs.appery.io/docs/snippets#actionsheetcontroller);
* [`AlertController`](https://docs.appery.io/docs/snippets#alertcontroller);
* [`PickerController`](https://docs.appery.io/docs/snippets#pickercontroller);
* [`MenuController`](https://docs.appery.io/docs/snippets#menucontroller);
* [`ModalController`](https://docs.appery.io/docs/snippets#modalcontroller);
* [`PopoverController`](https://docs.appery.io/docs/snippets#popovercontroller);
* [`LoadingController`](https://docs.appery.io/docs/snippets#loadingcontroller);
* [`ToastController`](https://docs.appery.io/docs/snippets#toastcontroller).

> 🚧 Note
>
> Note that all controller methods return a ***Promise***.

Wait until the method is completed:

```javascript
await controller.dismiss();
```

Get the data returned by the method:

```javascript
let result = await controller.dismiss();
```

### ActionSheetController

Available methods are as follows:

* `dismiss()` - dismisses the action sheet overlay after it has been presented;
* `onDidDismiss()` - returns a promise that resolves when the action sheet did dismiss;
* `onWillDismiss()` - returns a promise that resolves when the action sheet will dismiss;
* `present()` - presents the action sheet overlay after it has been created.

You can read more about `ActionSheetController` methods [here](https://ionicframework.com/docs/api/action-sheet#methods).

### AlertController

Available methods are as follows:

* `dismiss()` - dismisses the alert overlay after it has been presented;
* `onDidDismiss()` - returns a promise that resolves when the alert did dismiss;
* `onWillDismiss()` - returns a promise that resolves when the alert will dismiss;
* `present()` - presents the alert overlay after it has been created.

You can read more about AlertController methods [here](https://ionicframework.com/docs/api/alert#methods).

### PickerController

Available methods are as follows:

* `dismiss()` - dismisses the picker overlay after it has been presented;
* `getColumn()` - gets the column that matches the specified name;
* `onDidDismiss()` - returns a promise that resolves when the picker did dismiss;
* `onWillDismiss()` - returns a promise that resolves when the picker will dismiss;
* `present()` - presents the picker overlay after it has been created.

You can read more about PickerController methods [here](https://ionicframework.com/docs/api/picker#methods).

### MenuController

* `close()` - closes the menu. If the menu is already closed or can't be closed, it returns ***false***;
* `isActive()` - returns ***true*** if the menu is active;
* `isOpen()` - returns ***true*** if the menu is open;
* `open()` - opens the menu. If the menu is already open or it can't be opened, it returns ***false***;
* `setOpen()` - opens or closes the button. If the operation can't be completed successfully, it returns `false`;
* `toggle()` - toggles the menu. If the menu is already open, it will try to close. Otherwise, it will try to open it. If the operation can't be completed successfully, it returns ***false***.

You can read more about MenuController methods [here](https://ionicframework.com/docs/api/menu#methods).

### ModalController

* `dismiss()` - dismisses the modal overlay after it has been presented;
* `onDidDismiss()` - returns a promise that resolves when the modal did dismiss;
* `onWillDismiss()` - returns a promise that resolves when the modal will dismiss;
* `present()` - presents the modal overlay after it has been created.

You can read more about ModalController methods [here](https://ionicframework.com/docs/api/modal#methods).

### PopoverController

* `dismiss()` - dismisses the popover overlay after it has been presented;
* `onDidDismiss()` - returns a promise that resolves when the popover did dismiss;
* `onWillDismiss()` - returns a promise that resolves when the popover will dismiss;
* `present()` - presents the popover overlay after it has been created.

You can read more about PopoverController methods [here](https://ionicframework.com/docs/api/popover#methods).

### LoadingController

* `dismiss(options)` - dismisses the loading overlay after it has been presented;
* `onDidDismiss()` - returns a promise that resolves when the loading did dismiss;
* `onWillDismiss()` - returns a promise that resolves when the loading will dismiss;
* `present()` - presents the loading overlay after it has been created.

You can read more about LoadingController methods [here](https://ionicframework.com/docs/api/loading#methods).

### ToastController

* `dismiss(options)` - dismisses the toast overlay after it has been presented;
* `onDidDismiss()` - returns a promise that resolves when the toast did dismiss;
* `onWillDismiss()` - returns a promise that resolves when the toast will dismiss;
* `present()` - presents the toast overlay after it has been created.

You can read more about ToastController methods [here](https://ionicframework.com/docs/api/toast#methods).

## Loading present

This snippet shows loading on the page.

> 📘 info
>
> Loading is based on the Ionic [Loading](https://ionicframework.com/docs/api/loading) component.

```javascript Loading present
this.Apperyio.getController("LoadingController").create({
    message: 'Please wait...',
    spinner: 'crescent',
    duration: 2000
}).then(loading => loading.present());
```

### Options

Options that allow customizing the showed loading:

* `animated` - if set to ***true***, the loading indicator will animate;
* `backdropDismiss` - if set to ***true***, the loading indicator will be dismissed when the backdrop is clicked;
* `cssClass` - additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces;
* `duration` - number of milliseconds to wait before dismissing the loading indicator;
* `keyboardClose` - if set to ***true***, the keyboard will be automatically dismissed when the overlay is presented;
* `message` - optional text content to display in the loading indicator;
* `mode` - determines which platform styles to use (***ios*** or ***md***);
* `showBackdrop` - if set to ***true***, a backdrop will be displayed behind the loading indicator
* `spinner` - the name of the spinner to display;
* `translucent` - if set to ***true***, the loading indicator will be translucent. Only applies when the mode is set to ***ios*** and the device supports backdrop-filter.

Available spinner names are ***circles***, ***circular***, ***crescent***, ***dots***, ***lines***, ***lines-small***, ***null*** or ***undefined***.\
To hide loading, use the ***[Loading dismiss](https://docs.appery.io/docs/snippets#loading-dismisss)*** snippet.\
To have the possibility of controlling the loading, use the [`LoadingController`](https://docs.appery.io/docs/snippets#loadingcontroller) controller received with the ***[Get controller](https://docs.appery.io/docs/snippets#get-controller)*** snippet.

## Loading dismiss

This snippet hides loading on the page:

```javascript Loading dismiss
this.Apperyio.getController("LoadingController").dismiss();
```

## Toast present

This snippet shows a toast on the page:

> 📘 info
>
> Toast is based on the Ionic [Toast](https://ionicframework.com/docs/api/toast) component.

```javascript Toast present
this.Apperyio.getController("ToastController").create({
    header: 'Toast header',
    message: 'Click to Close',
    position: 'top',
    buttons: [{
        side: 'start',
        icon: 'star',
        text: 'Favorite',
        handler: () => {
            console.log('Favorite clicked');
        }
    }, {
        text: 'Done',
        role: 'cancel',
        handler: () => {
            console.log('Cancel clicked');
        }
    }]
}).then(toast => toast.present());
```

### Options

Options that allow customizing the showed toast:

* `animated` - if set to ***true***, the toast indicator will animate;
* `buttons` - an array of buttons for the toast;
* `color` - the color to use from your application's color palette;
* `cssClass` - additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces;
* `duration` - how many milliseconds to wait before hiding the toast. By default, it will show until `dismiss()` is called;
* `header` - header to be shown in the toast;
* `keyboardClose` - if set to ***true***, the keyboard will be automatically dismissed when the overlay is presented;
* `message` - message to be shown in the toast;
* `mode` - determines which platform styles to use (***ios*** or ***md***);
* `position` - the position of the toast on the screen;
* `translucent` - if set to ***true***, the toast will be translucent. This only applies when the mode is ***ios*** and the device supports backdrop-filter.

Default `color` options are: ***primary***, ***secondary***, ***tertiary***, ***success***, ***warning***, ***danger***, ***light***, ***medium***, and ***dark***.\
The default `position` options are: ***bottom***, ***middle***&#x6F;r ***top***.\
To hide the toast use the ***[Toast dismiss](https://docs.appery.io/docs/snippets#toast-dismiss)*** snippet.\
To have the possibility of controlling the toast, use the [`ToastController`](https://docs.appery.io/docs/snippets#toastcontroller) controller received by the ***[Get controller](https://docs.appery.io/docs/snippets#get-controller)*** snippet.

#### Buttons options:

* `text` - text of the button;
* `icon` - [Ionic icon](https://ionicons.com/) name to display in the close button;
* `side` - position (***start*** or ***end***) inside the toast where the close button will be shown;
* `role` - role of the element that is dismissing the toast. This can be useful in a button handler for determining which button was clicked to dismiss the toast (e.g. ***cancel*** or ***ok***);
* `cssClass` - additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces;
* `handler` - function invoking after clicking on the button.

## Toast dismiss

This snippet hides a toast on the page

```javascript Toast dismiss
this.Apperyio.getController("ToastController").dismiss();
```

## i18n set language

This snippet changes the language currently used:

```javascript i18n set language
this.Apperyio.translate.use("lang_name");
```

In the code above, the `lang_name` argument should be replaced with the actual language with the created dictionary for it (e.g. `en`).\
You can read more [here](https://github.com/ngx-translate).

> 📘 Want to know more?
>
> You can check [this](https://docs.appery.io/docs/ionic-5-multilingual-sample-app)tutorial that demonstrates how to use the ***i18n set language*** snippet and the ***ngx-translate*** third-party internationalization (`i18n`) library for building a multilingual Ionic app.

## i18n get translation

This snippet gets the instantly translated value of a key (or an array of keys):

```javascript i18n get translation
this.Apperyio.translate.instant("key"/*, interpolateParams*/);
```

The `interpolateParams` argument is an object of data that replaces variables of dictionaries.\
You can read more [here](https://github.com/ngx-translate).

## i18n get browser lang

This snippet gets the current browser language if available or throws `undefined` otherwise:

```javascript i18n get browser lang
this.Apperyio.translate.getBrowserLang();
```

You can read more [here](https://github.com/ngx-translate).

## Get variable

This snippet gets a global variable:

```javascript Get variable
let val = this.Apperyio.data.getVariable("varName");
```

In the code above, the `varName` argument should be replaced with the actual variable name\
Note that the snippet returns `undefined` unless the value of the variable with the same name is defined with the ***[Set variable](https://docs.appery.io/docs/snippets#set-variable)*** snippet.

For example, you can create a global variable and use it where needed using this helper:

```javascript
Apperyio.data.getVariable("myBoolVar1")
```

Check the screenshots below for how to do it:

<Image align="center" className="border" border={true} src="https://files.readme.io/c6e1f06-2023-03-03_12-08-51.png" />

<Image align="center" className="border" border={true} src="https://files.readme.io/6620ed0-2023-03-03_12-23-26.png" />

To add this variable, use the ***[Set variable](https://docs.appery.io/docs/snippets#set-variable)*** snippet.

## Set variable

<Image align="center" className="border" border={true} src="https://files.readme.io/41fc5fc-2023-03-03_12-16-15.png" />

This snippet sets a global variable:

```javascript Set variable
this.Apperyio.data.setVariable("varName", "some value");
```

In the code above, the `varName` argument should be replaced with the actual variable name, and `some value` should be replaced with the data used as the variable value.\
The value of the variable can be read with the ***[Get variable](https://docs.appery.io/docs/snippets#get-variable)*** snippet.

## Get from storage

This snippet gets data from the storage specified in the **Project > Model and Storage >[Storage](https://docs.appery.io/docs/6-model-and-storage#storage)** section.

> 📘 info
>
> Storage is based on [Data Storage](https://ionicframework.com/docs/angular/storage).

```javascript Get from storage
let val = await this.Apperyio.data.getStorage("storName");
```

In the code above, the `storName` argument should be replaced with the actual storage name.\
If no specified storage value is set, the snippet returns `null`.

## Set to storage

This snippet sets data to the storage specified in the **Project > Model and Storage >[Storage](https://docs.appery.io/docs/6-model-and-storage#storage)** section.

> 📘 info
>
> Storage is based on [Data Storage](https://ionicframework.com/docs/angular/storage).

```javascript Set to storage
await this.Apperyio.data.setStorage("storName", "some value");
```

In the code above, the `storName` argument should be replaced with the storage name and `some value` should be replaced with the data used as the storage value.

## Remove from storage

This snippet removes the storage specified in the **Project > Model and Storage >[Storage](https://docs.appery.io/docs/6-model-and-storage#storage)** section.

> 📘 info
>
> Storage is based on [Data Storage](https://ionicframework.com/docs/angular/storage).

```javascript Remove from storage
await this.Apperyio.data.removeStorage("storName");
```

In the code above, the `storName` argument should be replaced with the actual storage name.

## Preload ionic components

This snippet preloads some Ionic components (for example alert, select, etc., or the components that are initially hidden on the page (with `*ngIf`)) to get rid of delays when a component/overlay is shown for the first time.\
It can be selected for the ***[Run TypeScript](https://docs.appery.io/docs/5-event-handling#run-typescript)*** action.

```javascript Preload ionic components
this.Apperyio.preload.components([/*"ion-modal"*/]);
```

## Preload ionic icons

This snippet preloads some Ionic Icons to get rid of delays when a component/overlay is shown for the first time.\
It can be selected for the ***[Run TypeScript](https://docs.appery.io/docs/5-event-handling#run-typescript)*** action.

```javascript Preload ionic icons
this.Apperyio.preload.icons([/*"alarm"*/]);
```

## Set theme

This snippet allows setting the needed color [theme](https://docs.appery.io/docs/theme-generator). The theme name needs to be provided:

```javascript Set theme
this.Apperyio.theme.set("themeName");
```

## Get current theme

This snippet applies the currently selected color [theme](https://docs.appery.io/docs/3-creating-an-app-ui-styling-apps#adding-themes-to-app).

```javascript Get current theme
let themeName = this.Apperyio.theme.getCurrent();
```

## Reorder complete

This snippet completes the **[ReorderGroup](https://docs.appery.io/docs/ionic-5-ui-components-properties#reordergroup)** component data and can be selected for the ***[Run TypeScript](https://docs.appery.io/docs/5-event-handling#run-typescript)*** action:

```typescript Reorder complete
// console.log('Dragged from index', event.detail.from, 'to', event.detail.to);
// change the 'list' to the name of created variable with array of reorder items
// this.list = event.detail.complete(this.list);
event.detail.complete();
```

[Appery.io](https://appery.io/) has the *[Automatic app update](https://docs.appery.io/docs/appexport-auto-update)* feature, which means you can update apps that your end-users have already installed on the device and this can be done without going through an app store.\
But in some cases, you may want to control the update flow from the JavaScript side. For this, we offer the following options:

* ***[Get autoupdate version](https://docs.appery.io/docs/snippets#get-autoupdate-server-version)***
* ***[Get autoupdate server version](https://docs.appery.io/docs/ionic-5-snippets#get-autoupdate-version)***
* ***[Download latest autoupdate version](https://docs.appery.io/docs/snippets#download-latest-autoupdate-version)***
* ***[Install latest autoupdate version](https://docs.appery.io/docs/snippets#install-latest-autoupdate-version)***.

## Get autoupdate version

On every launch, this snippet will check the client autoupdate version:

```typescript Get autoupdate version
// return an object with properties:
// status - indicates whether the getAutoupdateVersion call was successful,
//          available value: "Success" or "Error"
// data - shows the autoupdate version, if the 'status' is set to "Success"
// message - shows the error message if the 'status' is set to "Error"
const data = await this.Apperyio.hotPush.getAutoupdateVersion();
if (data.status === "Error") {
    console.log(data.message)
} else {
    console.log(data.data)
};
```

## Get autoupdate server version

This plug-in connects to your server on startup and checks the server autoupdate version:

```typescript Get autoupdate server version
// return an object with properties:
// status - indicates whether the getAutoupdateServerVersionSync call was successful,
//          available value: "Success" or "Error"
// data - shows the autoupdate server version, if the 'status' is set to "Success"
// message - shows the error message if the 'status' is set to "Error
const data = await this.Apperyio.hotPush.getAutoupdateServerVersionSync();
if (data.status === "Error") {
    console.log(data.message)
} else {
    console.log(data.data)
};
```

## Download latest autoupdate version

To automatically download the update to the device, use the following method:

```typescript Download latest autoupdate version
// return an object with properties:
// status - indicates whether the autoupdateDownloadLatestVersion call was successful,
//          available value: "Success" or "Error"
// data - shows the latest autoupdate version, if the 'status' is set to "Success"
// message - shows the error message if the 'status' is set to "Error
const data = await this.Apperyio.hotPush.autoupdateDownloadLatestVersion();
if (data.status === "Error") {
    console.log(data.message)
} else {
    console.log(data.data)
};
```

## Install latest autoupdate version

Use this method to install the latest autoupdate version on the device:

```typescript Install latest autoupdate version
// return an object with properties:
// status - indicates whether the autoupdateInstallLatestVersion call was successful,
//          available value: "Success" or "Error"
// message - shows the error message if the 'status' is set to "Error
const data = await this.Apperyio.hotPush.autoupdateInstallLatestVersion();
if (data.status === "Error") {
    console.log(data.message)
} else {
    console.log(data.status)
};
```

## Alert present

This snippet creates and shows an **Alert** component based on the [Ionic Alert](https://ionicframework.com/docs/api/alert) component:

```typescript Alert present
await (async () => {
    let options = {
        // additional classes to apply for custom CSS
        // if multiple classes are provided they should be separated by spaces
        'cssClass': '',
        // the main title in the heading of the alert
        'header': 'Alert header',
        // the main message to be displayed in the alert.
        // message can accept either plaintext or HTML as a string.
        // to display characters normally reserved for HTML, they must be escaped
        'message': 'message',
        // the subtitle in the heading of the alert. Displayed under the title
        'subHeader': 'Alert sub header',
        // array of buttons to be added to the alert (string | AlertButton)
        'buttons': ['OK']
    }
    let controller = this.Apperyio.getController('AlertController');
    const alert = await controller.create(options);
    return await alert.present();
})();
```

You are free to customize the alert properties like header, subheader, and/or message.