Ionic Action Sheet Example

ionic-action-sheet-example

In this tutorial, we're going to learn how to create ActionSheet using Ionic Framework.

Goal:

  • Create a button
  • When user pressed button, open action sheet with 2 option

    • Option 1: Access Camera
    • Option 2: Access Gallery
  • Display Output in console

STEPS

Create New Ionic Project

ionic start ActionSheet blank
cd ActionSheet

Create a button with click functionality inside src/app/home/home.html

<ion-button fill="outline" (click)="openActionSheet()">Open Action Sheet</ion-button>

Open src/app/home/home.ts

openActionSheet() {
    this.actionCtrl.create({
      buttons: [
        {
          text: "Open Camera",
          icon: 'camera',
          handler: () => {
            this.message = "Camera Pressed";
          }
        },
        {
          text: "Open Gallery",
          icon: 'grid',
          handler: () => {
            this.message = "Gallery Pressed";
          }
        },
        {
          text: "Cancel",
          role: 'cancel'
        }
      ]
    }).then(ac => ac.present())
  }

When the user pressed the button, we call openActionSheet() function.so this display the action sheets with three options such as Open Camera, Open Gallery and cancel button.we also added the icons.

Whenever user pressed those button, we update the message.

Ionic Action Sheet Example Source code

src/app/home/home.html

<ion-header>
    <ion-toolbar color="primary">
        <ion-title>
            codesundar.com
        </ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>
    <div class="center">
        {{ message }}
        <ion-button fill="outline" (click)="openActionSheet()">Open Action Sheet</ion-button>
    </div>
</ion-content>

src/app/home/home.ts

import { Component } from '@angular/core';
import { ActionSheetController } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  message;

  constructor(
    private actionCtrl: ActionSheetController
  ) { }

  openActionSheet() {
    this.actionCtrl.create({
      buttons: [
        {
          text: "Open Camera",
          icon: 'camera',
          handler: () => {
            this.message = "Camera Pressed";
          }
        },
        {
          text: "Open Gallery",
          icon: 'grid',
          handler: () => {
            this.message = "Gallery Pressed";
          }
        },
        {
          text: "Cancel",
          role: 'cancel'
        }
      ]
    }).then(ac => ac.present())
  }
}

Output

ionic-action-sheet-example

ionic action sheet example

Reference