Skip to main content

Working with Alert Components

1. Creating Alert

Example: Basic Alert

import { AlertController } from '@ionic/angular';

async function showAlert() {
  const alert = await alertController.create({
    header: 'Alert',
    message: 'This is an alert message.',
    buttons: ['OK']
  });

  await alert.present();
}
Property Description Values
header Alert title string
message Alert content string
buttons Alert buttons Array<string | AlertButton>
cssClass Custom CSS class for styling string
backdropDismiss Whether to dismiss on backdrop tap boolean
Note: The alertController must be imported from @ionic/angular.

2. Configuring Alert Header

Property Description Default Notes
header Text to display in the alert header null Can include HTML tags for formatting
subHeader Additional text below the header null Useful for providing context or details

Example: Basic Alert Header

const alert = await alertController.create({
  header: 'Welcome',
  subHeader: 'Please review the following information'
});

await alert.present();

3. Adding Alert Message

Property Description Default Notes
message The main message content of the alert '' Can include HTML tags for formatting
cssClass Custom CSS class to style the alert '' Applies to the alert wrapper element
duration Time in milliseconds before alert auto-closes 0 Set to 0 for manual close

Example: Basic Alert Message

import { AlertController } from '@ionic/angular';

async presentAlert() {
  const alert = await this.alertController.create({
    header: 'Alert',
    message: 'This is an alert message.',
    buttons: ['OK']
  });

  await alert.present();
}

Example: Alert with HTML Message

async presentAlertWithHtml() {
  const alert = await this.alertController.create({
    header: 'Terms and Conditions',
    message: '<p>By continuing, you agree to our <a href="#">Terms of Service</a>.</p>',
    buttons: ['Accept', 'Decline']
  });

  await alert.present();
}

4. Configuring Alert Inputs

Property Description Values Notes
inputs List of input elements to show in the alert Array of objects with type, name, placeholder, and value Each input object can have type as text, password, email, number, or textarea
type Input type text, password, email, number, textarea Defaults to text
name Input name for identifying the value in the callback String Used to retrieve input values in onDidDismiss
placeholder Placeholder text for the input String Shown when input is empty
value Initial value of the input String or number Can be set to pre-fill the input field

Example: Configuring Alert Inputs

const alert = await alertController.create({
  header: 'Enter Details',
  inputs: [
    {
      name: 'username',
      type: 'text',
      placeholder: 'Enter your username'
    },
    {
      name: 'password',
      type: 'password',
      placeholder: 'Enter your password'
    }
  ],
  buttons: [
    {
      text: 'Cancel',
      role: 'cancel'
    },
    {
      text: 'Submit',
      handler: (data) => {
        console.log('Username:', data.username);
        console.log('Password:', data.password);
      }
    }
  ]
});

await alert.present();

5. Adding Alert Buttons

Property Description Values
buttons Array of button configurations for the alert Array<AlertButton>

Example: Basic Alert with Buttons

import { AlertController } from '@ionic/angular';

async presentAlert() {
  const alert = await this.alertController.create({
    header: 'Alert',
    message: 'This is an alert with buttons.',
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel'
      },
      {
        text: 'OK',
        handler: () => {
          console.log('OK clicked');
        }
      }
    ]
  });

  await alert.present();
}

Example: Alert with Multiple Buttons

async presentAlertWithOptions() {
  const alert = await this.alertController.create({
    header: 'Options',
    message: 'Choose an option',
    buttons: [
      {
        text: 'Option 1',
        handler: () => {
          console.log('Option 1 selected');
        }
      },
      {
        text: 'Option 2',
        handler: () => {
          console.log('Option 2 selected');
        }
      },
      {
        text: 'Dismiss',
        role: 'cancel'
      }
    ]
  });

  await alert.present();
}

6. Presenting Alert

Example: Basic Alert

import { AlertController } from '@ionic/angular';

async presentAlert() {
  const alert = await this.alertController.create({
    header: 'Alert',
    message: 'This is an alert message.',
    buttons: ['OK']
  });

  await alert.present();
}
Property Description Values
header Alert title string
message Alert content string
buttons Alert buttons Array<string | AlertButton>
Note: The alertController must be injected into your component or service to use it.

7. Dismissing Alert

Property Values Description
alertController AlertController The controller used to present and dismiss alerts
dismiss() () => Promise<void> Method to dismiss the alert programmatically

Example: Dismissing Alert Programmatically

import { AlertController } from '@ionic/angular';

async function dismissAlert(alertController: AlertController) {
  await alertController.dismiss();
}
Note: The dismiss() method can be called with optional data and a role to provide context to the dismissing event.

8. Using Confirm Dialogs

Confirm dialogs are used to get a yes/no response from the user, typically for actions that could be destructive or require explicit confirmation.

Property Description Default
header Dialog title text null
message Dialog body content null
buttons Array of button configurations []
cssClass Custom CSS classes for styling null

Example: Basic Confirm Dialog

<ion-confirm-alert
  header="Confirm Deletion"
  message="Are you sure you want to delete this item?"
  buttons={[
    {
      text: "Cancel",
      role: "cancel"
    },
    {
      text: "Delete",
      role: "destructive"
    }
  ]}
></ion-confirm-alert>

Example: Confirm with Custom Button Labels

<ion-confirm-alert
  header="Save Changes?"
  message="You have unsaved changes. Do you want to save them?"
  buttons={[
    {
      text: "Save",
      handler: () => {
        console.log("Saving changes...");
      }
    },
    {
      text: "Discard",
      role: "cancel"
    }
  ]}
></ion-confirm-alert>
Note: The role property can be used to style buttons differently (e.g., cancel, destructive, or primary). Buttons with role: 'cancel' typically close the dialog without executing any action.
Warning: Ensure that destructive actions (like deletion) are confirmed by the user before proceeding. Misuse of confirm dialogs can lead to accidental data loss.

9. Using Prompt Dialogs

Property Description Default Notes
header Dialog title null Optional
message Dialog message content null Required if no input field
inputs Array of input fields (text, email, password) [] Optional array of input configurations
buttons Array of button configurations [] Required array of button objects
cssClass Custom CSS class for styling null Optional string or array of strings

Example: Basic Prompt Dialog

import { alertController } from '@ionic/core';

const alert = await alertController.create({
  header: 'Enter your name',
  message: 'Please provide your full name',
  inputs: [
    {
      type: 'text',
      placeholder: 'Full Name'
    }
  ],
  buttons: [
    {
      text: 'Cancel',
      role: 'cancel'
    },
    {
      text: 'OK',
      handler: (data) => {
        console.log('Name entered:', data);
      }
    }
  ]
});

await alert.present();

Example: Prompt with Multiple Inputs

import { alertController } from '@ionic/core';

const alert = await alertController.create({
  header: 'Account Setup',
  inputs: [
    {
      type: 'text',
      name: 'username',
      placeholder: 'Username'
    },
    {
      type: 'password',
      name: 'password',
      placeholder: 'Password'
    }
  ],
  buttons: [
    {
      text: 'Cancel'
    },
    {
      text: 'Submit',
      handler: (data) => {
        console.log('Credentials:', data);
      }
    }
  ]
});

await alert.present();
Note: The handler function in the button configuration receives the input values as an object where keys match the name property of each input field.

10. Handling Alert Events

Event Description Details
didPresent Fires after the alert is presented Useful for triggering actions once the alert is visible to the user
willDismiss Fires before the alert is dismissed Allows you to prevent dismissal or perform cleanup
didDismiss Fires after the alert is dismissed Useful for post-dismissal logic or state updates

Example: Listening to Alert Events

<ion-alert-controller></ion-alert-controller>
<ion-button onclick="presentAlert()">Show Alert</ion-button>

async function presentAlert() {
  const alertController = document.querySelector("ion-alert-controller");
  const alert = await alertController.create({
    header: "Alert Title",
    message: "This is an alert.",
    buttons: ["OK"]
  });

  alert.addEventListener("didDismiss", (ev) => {
    console.log("Alert dismissed with role:", ev.detail.role);
  });

  await alert.present();
}

Was this article helpful?