Working with Utilities and Helpers
1. Using IonicSafeString
The IonicSafeString utility is used to safely handle and sanitize strings in Ionic applications, particularly when dealing with content that may contain HTML or potentially unsafe characters.
| Property | Description | Usage |
|---|---|---|
| value | The string to be sanitized. | new IonicSafeString('<script>alert("XSS")</script>'); |
| isTrusted | Indicates whether the string is trusted and should not be sanitized. | true or false |
Example: Creating an IonicSafeString
import { IonicSafeString } from '@ionic/angular';
const unsafeContent = '<script>alert("XSS")</script>';
const safeContent = new IonicSafeString(unsafeContent);
console.log(safeContent.value); // <script>alert("XSS")</script>
Example: Using isTrusted Flag
import { IonicSafeString } from '@ionic/angular';
const trustedContent = '<h1>Hello World</h1>';
const safeContent = new IonicSafeString(trustedContent, true);
console.log(safeContent.value); // <h1>Hello World</h1>
2. Implementing isPlatform Check
| Method | Description | Usage |
|---|---|---|
| isPlatform(platform: string) | Checks if the current platform matches the provided platform name | import { isPlatform } from '@ionic/core';\n\nif (isPlatform('ios')) {\n console.log('Running on iOS');\n} |
| isPlatform(platform: string) | Checks if the current platform matches the provided platform name | import { isPlatform } from '@ionic/core';\n\nif (isPlatform('android')) {\n console.log('Running on Android');\n} |
isPlatform function is useful for conditional rendering or behavior based on the device platform.3. Using getPlatforms Method
The getPlatforms method is a utility function provided by Ionic that helps developers determine the current platform (e.g., mobile, desktop, browser) at runtime. This is particularly useful for applying platform-specific logic or styling.
| Method | Description | Return Type |
|---|---|---|
| getPlatforms() | Returns an array of platform names the app is running on. | string[] |
Example: Detecting Platform
import { getPlatforms } from '@ionic/core';
const platforms = getPlatforms();
console.log(platforms); // e.g. ['mobile', 'ios']
getPlatforms method returns a list of platform identifiers that can be used to conditionally apply logic or styles based on the current environment.
4. Creating Utility Services
Example: Basic Utility Service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UtilityService {
formatDate(date: Date): string {
return date.toLocaleDateString();
}
generateId(): string {
return Math.random().toString(36).substr(2, 9);
}
}
| Method | Description | Return Type |
|---|---|---|
| formatDate(date) | Formats a Date object into a readable string | string |
| generateId() | Generates a random ID string | string |
providedIn: 'root'.5. Using Animation Utils
The Ionic framework provides a set of utility functions and helpers to manage animations within your application. These utilities simplify the process of creating and controlling animations, making it easier to enhance user experience with smooth transitions and effects.
| Utility | Description | Usage |
|---|---|---|
| ionAnimation | Creates a new animation instance for use with Ionic components. | import { ionAnimation } from '@ionic/core'; |
| createAnimation | Function to create an animation object with various configuration options. | const animation = createAnimation(); |
| AnimationBuilder | Interface for building animations with custom properties and keyframes. | const builder = new AnimationBuilder(); |
Example: Creating a Basic Animation
import { createAnimation } from '@ionic/core';
const animation = createAnimation();
animation.addElement(document.querySelector('.my-element'));
animation.setDuration(500);
animation.setEasing('ease-in-out');
animation.fromTo('opacity', 0, 1);
animation.play();
Example: Using Animation with Keyframes
import { createAnimation } from '@ionic/core';
const animation = createAnimation();
animation.addElement(document.querySelector('.my-element'));
animation.keyframes([
{ offset: 0, transform: 'translateX(0)', opacity: 0 },
{ offset: 0.5, transform: 'translateX(100px)', opacity: 0.5 },
{ offset: 1, transform: 'translateX(200px)', opacity: 1 }
]);
animation.play();
6. Implementing Date Utilities
| Method | Description | Example |
|---|---|---|
| formatDate() | Formats a date object or string into a readable format | import { formatDate } from '@ionic/utils';<br><br>const date = new Date('2025-04-05');<br>const formatted = formatDate(date, 'MM/DD/YYYY');<br>console.log(formatted); // 04/05/2025 |
| isToday() | Checks if a given date is today | import { isToday } from '@ionic/utils';<br><br>const today = new Date();<br>const isTodayResult = isToday(today);<br>console.log(isTodayResult); // true |
| addDays() | Adds or subtracts days from a date | import { addDays } from '@ionic/utils';<br><br>const date = new Date('2025-04-05');<br>const newDate = addDays(date, 5);<br>console.log(newDate.toISOString().split('T')[0]); // 2025-04-10 |
| isSameDay() | Checks if two dates are the same day | import { isSameDay } from '@ionic/utils';<br><br>const date1 = new Date('2025-04-05');<br>const date2 = new Date('2025-04-05');<br>const sameDay = isSameDay(date1, date2);<br>console.log(sameDay); // true |
@ionic/utils package and provide consistent date handling across Ionic applications.7. Using String Helpers
| Helper | Description | Example |
|---|---|---|
| capitalize | Capitalizes the first letter of a string | import { capitalize } from '@ionic/utils';\n\nconsole.log(capitalize('hello')); // 'Hello' |
| camelCase | Converts a string to camelCase format | import { camelCase } from '@ionic/utils';\n\nconsole.log(camelCase('hello world')); // 'helloWorld' |
| kebabCase | Converts a string to kebab-case format | import { kebabCase } from '@ionic/utils';\n\nconsole.log(kebabCase('hello world')); // 'hello-world' |
| snakeCase | Converts a string to snake_case format | import { snakeCase } from '@ionic/utils';\n\nconsole.log(snakeCase('hello world')); // 'hello_world' |
| titleCase | Converts a string to Title Case format | import { titleCase } from '@ionic/utils';\n\nconsole.log(titleCase('hello world')); // 'Hello World' |
| truncate | Truncates a string to a specified length with an optional suffix | import { truncate } from '@ionic/utils';\n\nconsole.log(truncate('This is a long string', 10)); // 'This is...' |
8. Creating Custom Pipes
Pipes in Ionic (Angular) are used to transform data for display. Creating custom pipes allows you to extend this functionality with your own logic.
| Property | Description | Example |
|---|---|---|
| name | The name of the pipe, used in templates | customPipe |
| pure | Whether the pipe is pure (default: true). Pure pipes only recompute when input values change | false for impure pipes |
Example: Creating a Custom Pipe
@Pipe({
name: 'customPipe',
pure: true
})
export class CustomPipe implements PipeTransform {
transform(value: string, ...args: any[]): string {
return value ? value.toUpperCase() : '';
}
}
Example: Using the Custom Pipe in a Template
<ion-item>
<ion-label>{{ 'hello world' | customPipe }}</ion-label>
</ion-item>
9. Using Array Utilities
The Ionic framework provides several utility functions for working with arrays, which are commonly used in mobile and web applications. These utilities help developers manipulate and filter data efficiently.
| Utility | Description | Usage |
|---|---|---|
| arrayFrom | Creates a new array from an array-like or iterable object. | import { arrayFrom } from '@ionic/core';<br><br>const nodeList = document.querySelectorAll('div');<br>const array = arrayFrom(nodeList); |
| arrayPush | Pushes one or more elements to the end of an array and returns the new length. | import { arrayPush } from '@ionic/core';<br><br>let arr = [1, 2, 3];<br>const newLength = arrayPush(arr, 4, 5);<br>// arr is now [1, 2, 3, 4, 5], newLength = 5 |
| arraySplice | Changes the contents of an array by removing or replacing existing elements and/or adding new elements. | import { arraySplice } from '@ionic/core';<br><br>let arr = [1, 2, 3, 4, 5];<br>arraySplice(arr, 2, 1, 'a', 'b');<br>// arr is now [1, 2, 'a', 'b', 4, 5] |
Example: Filtering Arrays with Utility Functions
import { arrayFilter } from '@ionic/core';<br><br>const numbers = [1, 2, 3, 4, 5, 6];<br>const evenNumbers = arrayFilter(numbers, num => num % 2 === 0);<br>// evenNumbers is [2, 4, 6]
10. Implementing Validation Helpers
| Helper | Description | Usage | Notes |
|---|---|---|---|
| isEmail | Checks if a string is a valid email address | isEmail('user@example.com') |
Returns true if valid, false otherwise |
| isURL | Validates if a string is a valid URL | isURL('https://example.com') |
Supports HTTP, HTTPS, and FTP protocols |
| isNumeric | Checks if a string contains only numeric characters | isNumeric('12345') |
Accepts integers and floats |
| isAlpha | Verifies if a string contains only alphabetic characters | isAlpha('abc') |
Case-sensitive validation |
| isAlphanumeric | Ensures a string is alphanumeric | isAlphanumeric('abc123') |
Allows letters and numbers only |
Example: Using Validation Helpers
import { isEmail, isURL } from '@ionic/utils';
const email = 'user@example.com';
const url = 'https://example.com';
if (isEmail(email)) {
console.log('Valid email');
}
if (isURL(url)) {
console.log('Valid URL');
}
@ionic/utils package and can be used in both frontend and backend environments.