Create a custom ionic alert with progress bar using ionic 7 angular

3 min read 13-09-2024
Create a custom ionic alert with progress bar using ionic 7 angular


Creating a Custom Ionic Alert with Progress Bar in Ionic 7 and Angular

Ionic's built-in alert component is great for displaying simple messages, but sometimes you need more visual feedback, like a progress bar to indicate an ongoing process. This article will guide you through creating a custom Ionic alert component with a progress bar, enhancing your app's user experience.

The Challenge:

Let's say you want to display a loading alert while your app fetches data from an API. Instead of simply showing a "Loading..." text, you'd like to include a progress bar to visually represent the progress.

Original Code:

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

// ... inside your component

async presentAlert() {
  const alert = await this.alertController.create({
    header: 'Loading...',
    message: 'Please wait while we fetch data...',
    buttons: ['OK'],
  });

  await alert.present();
}

Solution:

Here's how you can create a custom alert with a progress bar in Ionic 7:

1. Create a Custom Alert Component:

Start by creating a new component named progress-alert.component.ts in your project. This component will be responsible for displaying the custom alert with the progress bar.

import { Component, OnInit, Input } from '@angular/core';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-progress-alert',
  templateUrl: './progress-alert.component.html',
  styleUrls: ['./progress-alert.component.scss'],
})
export class ProgressAlertComponent implements OnInit {
  @Input() message: string;
  @Input() progressValue: number;

  constructor(private alertController: AlertController) {}

  ngOnInit() {}

  async presentAlert() {
    const alert = await this.alertController.create({
      header: 'Loading...',
      message: `<div class="progress-bar"><div class="progress-bar-fill" style="width: ${this.progressValue}%;"></div></div>${this.message}`,
      buttons: ['OK'],
      cssClass: 'custom-alert',
    });
    await alert.present();
  }
}

2. Design the Custom Alert:

Next, create a corresponding template progress-alert.component.html:

<ion-content>
  <div class="alert-content">
    <div class="alert-header">Loading...</div>
    <div class="progress-bar-container">
      <div class="progress-bar">
        <div class="progress-bar-fill" [style.width.%]="progressValue"></div>
      </div>
    </div>
    <div class="alert-message">{{ message }}</div>
  </div>
</ion-content>

And define some basic styles in progress-alert.component.scss:

.custom-alert {
  .alert-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px;
  }

  .alert-header {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 8px;
  }

  .progress-bar-container {
    width: 100%;
    height: 8px;
    margin-bottom: 8px;
    background-color: #eee;
    border-radius: 4px;
  }

  .progress-bar {
    height: 100%;
    background-color: #4CAF50;
    border-radius: 4px;
  }

  .alert-message {
    font-size: 14px;
  }
}

3. Use the Custom Alert Component:

In your component where you want to use the alert, import the ProgressAlertComponent:

import { ProgressAlertComponent } from './progress-alert.component'; 

// ... inside your component

async presentAlert() {
    const alert = await this.alertController.create({
      component: ProgressAlertComponent,
      componentProps: { 
        message: 'Please wait while we fetch data...',
        progressValue: 0 
      }
    });
    await alert.present();

    // ... update progressValue in componentProps (e.g., using intervals) ... 
  }

4. Update Progress Value:

You can update the progress value dynamically using a timer or by tracking the progress of your data fetching process. For example:

// ... inside your component

async presentAlert() {
  // ... (present alert as shown above) ...

  let progress = 0;
  const interval = setInterval(() => {
    progress += 10;
    alert.componentInstance.progressValue = progress;

    if (progress >= 100) {
      clearInterval(interval);
    }
  }, 1000); // Update every 1 second

  // ... (handle data fetching and close the alert when done) ...
}

Additional Notes:

  • You can customize the alert's appearance and progress bar style further by modifying the CSS in progress-alert.component.scss.
  • Consider adding error handling to gracefully manage cases where the data fetching fails.
  • This is a simple example. You can add more features to your custom alert, such as adding a cancel button or displaying specific progress information.

Conclusion:

By creating a custom alert component with a progress bar, you can provide users with more informative and engaging feedback during long-running processes. This enhances the user experience and improves the overall usability of your Ionic application. Remember to customize the alert to match your app's design and functionality for a seamless integration.