본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

알림 (ion-alert)

원문 보기 위키 갱신

알림(Alert)은 사용자에게 정보를 보여 주거나 입력을 통해 정보를 수집하는 다이얼로그예요. 앱 콘텐츠 위에 나타나며, 사용자가 앱과 상호작용을 재개하려면 직접 닫아야 해요. 선택적으로 header, subHeader, message를 가질 수 있어요.

출처: 문서

본문

Encapsulation: scoped

알림은 사용자에게 정보를 제시하거나 입력을 통해 사용자로부터 정보를 수집하는 다이얼로그예요. 알림은 앱 콘텐츠 위에 나타나며, 사용자가 앱과 상호작용을 재개하려면 수동으로 닫아야 해요. 선택적으로 header, subHeader, message를 가질 수 있어요.

ion-alert는 템플릿에 컴포넌트를 직접 작성해서 사용할 수 있어요. 이렇게 하면 Alert를 표시하기 위해 연결해야 하는 핸들러 수가 줄어들어요.

JavaScript

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert
  trigger="present-alert"
  header="A Short Title Is Best"
  sub-header="A Sub Header Is Optional"
  message="A message should be a short, complete sentence."
></ion-alert>

<script>
  const alert = document.querySelector('ion-alert');
  alert.buttons = ['Action'];
</script>

Angular

src/app/example.component.html

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert
  trigger="present-alert"
  header="A Short Title Is Best"
  subHeader="A Sub Header Is Optional"
  message="A message should be a short, complete sentence."
  [buttons]="alertButtons"
></ion-alert>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonAlert, IonButton } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonAlert, IonButton],
})
export class ExampleComponent {
  alertButtons = ['Action'];
}

React

import React from 'react';
import { IonAlert, IonButton } from '@ionic/react';

function Example() {
  return (
    <>
      <IonButton id="present-alert">Click Me</IonButton>
      <IonAlert
        trigger="present-alert"
        header="A Short Title Is Best"
        subHeader="A Sub Header Is Optional"
        message="A message should be a short, complete sentence."
        buttons={['Action']}
      ></IonAlert>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button id="present-alert">Click Me</ion-button>
  <ion-alert
    trigger="present-alert"
    header="A Short Title Is Best"
    sub-header="A Sub Header Is Optional"
    message="A message should be a short, complete sentence."
    :buttons="alertButtons"
  ></ion-alert>
</template>

<script setup lang="ts">
  import { IonAlert, IonButton } from '@ionic/vue';

  const alertButtons = ['Action'];
</script>

Using isOpen

ion-alert의 isOpen 프로퍼티를 사용하면 개발자가 앱 상태에서 Alert의 표시 상태를 제어할 수 있어요. 즉 isOpen이 true로 설정되면 Alert가 표시되고, false로 설정되면 Alert가 닫혀요.

isOpen은 단방향 데이터 바인딩을 사용해요. 그래서 Alert가 닫혀도 자동으로 false로 설정되지는 않아요. 개발자는 ionAlertDidDismiss나 didDismiss 이벤트를 리슨해서 isOpen을 false로 설정해야 해요. 이유는 ion-alert의 내부가 애플리케이션 상태와 밀접하게 결합되는 것을 막기 위해서예요. 단방향 데이터 바인딩에서는 Alert가 반응형 변수가 제공하는 boolean 값에만 신경 쓰면 돼요. 양방향 데이터 바인딩에서는 Alert가 boolean 값뿐 아니라 반응형 변수 자체의 존재까지 신경 써야 해요. 이는 비결정적 동작을 유발하고 앱을 디버깅하기 어렵게 만들 수 있어요.

JavaScript

<ion-button onclick="alert.isOpen = true">Click Me</ion-button>
<ion-alert
  header="A Short Title Is Best"
  sub-header="A Sub Header Is Optional"
  message="A message should be a short, complete sentence."
></ion-alert>

<script>
  const alert = document.querySelector('ion-alert');

  alert.buttons = ['Action'];
  alert.addEventListener('ionAlertDidDismiss', () => {
    alert.isOpen = false;
  });
</script>

Angular

src/app/example.component.html

<ion-button (click)="setOpen(true)">Click Me</ion-button>
<ion-alert
  [isOpen]="isAlertOpen"
  header="A Short Title Is Best"
  subHeader="A Sub Header Is Optional"
  message="A message should be a short, complete sentence."
  [buttons]="alertButtons"
  (didDismiss)="setOpen(false)"
></ion-alert>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonAlert, IonButton } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonAlert, IonButton],
})
export class ExampleComponent {
  isAlertOpen = false;
  alertButtons = ['Action'];

  setOpen(isOpen: boolean) {
    this.isAlertOpen = isOpen;
  }
}

React

import React, { useState } from 'react';
import { IonAlert, IonButton } from '@ionic/react';

function Example() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <IonButton onClick={() => setIsOpen(true)}>Click Me</IonButton>
      <IonAlert
        isOpen={isOpen}
        header="A Short Title Is Best"
        subHeader="A Sub Header Is Optional"
        message="A message should be a short, complete sentence."
        buttons={['Action']}
        onDidDismiss={() => setIsOpen(false)}
      ></IonAlert>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button @click="setOpen(true)">Click Me</ion-button>
  <ion-alert
    :is-open="isOpen"
    header="A Short Title Is Best"
    sub-header="A Sub Header Is Optional"
    message="A message should be a short, complete sentence."
    :buttons="alertButtons"
    @didDismiss="setOpen(false)"
  ></ion-alert>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { IonAlert, IonButton } from '@ionic/vue';

  const isOpen = ref(false);
  const alertButtons = ['Action'];

  const setOpen = (state: boolean) => {
    isOpen.value = state;
  };
</script>

Controller Alerts

alertController는 Alert가 언제 표시되고 닫힐지에 대해 더 세밀한 제어가 필요할 때 사용할 수 있어요.

JavaScript

<ion-button onclick="presentAlert()">Click Me</ion-button>

<script>
  async function presentAlert() {
    const alert = document.createElement('ion-alert');
    alert.header = 'A Short Title Is Best';
    alert.subHeader = 'A Sub Header Is Optional';
    alert.message = 'A message should be a short, complete sentence.';
    alert.buttons = ['Action'];

    document.body.appendChild(alert);
    await alert.present();
  }
</script>

Angular

src/app/example.component.html

<ion-button (click)="presentAlert()">Click Me</ion-button>

src/app/example.component.ts

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

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton],
})
export class ExampleComponent {
  constructor(private alertController: AlertController) {}

  async presentAlert() {
    const alert = await this.alertController.create({
      header: 'A Short Title Is Best',
      subHeader: 'A Sub Header Is Optional',
      message: 'A message should be a short, complete sentence.',
      buttons: ['Action'],
    });

    await alert.present();
  }
}

React

import React from 'react';
import { IonButton, useIonAlert } from '@ionic/react';

function Example() {
  const [presentAlert] = useIonAlert();

  return (
    <IonButton
      onClick={() =>
        presentAlert({
          header: 'A Short Title Is Best',
          subHeader: 'A Sub Header Is Optional',
          message: 'A message should be a short, complete sentence.',
          buttons: ['Action'],
        })
      }
    >
      Click Me
    </IonButton>
  );
}
export default Example;

Vue

<template>
  <ion-button @click="presentAlert">Click Me</ion-button>
</template>

<script setup lang="ts">
  import { IonButton, alertController } from '@ionic/vue';

  const presentAlert = async () => {
    const alert = await alertController.create({
      header: 'A Short Title Is Best',
      subHeader: 'A Sub Header Is Optional',
      message: 'A message should be a short, complete sentence.',
      buttons: ['Action'],
    });

    await alert.present();
  };
</script>

Buttons

buttons 배열에서 각 버튼은 text와 선택적으로 handler 프로퍼티를 포함해요. handler가 false를 반환하면 버튼을 클릭해도 alert가 자동으로 닫히지 않아요. 모든 버튼은 buttons 배열에 추가된 순서대로 왼쪽에서 오른쪽으로 표시돼요. 참고: 맨 오른쪽 버튼(배열의 마지막 요소)이 메인 버튼이에요.

선택적으로 버튼에 cancel 같은 role 프로퍼티를 추가할 수 있어요. 버튼 중 하나에 cancel 역할이 있다면, alert가 백드롭을 탭해서 닫힐 때 cancel 역할을 가진 버튼의 핸들러가 실행돼요.

JavaScript

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert trigger="present-alert" header="Alert!"></ion-alert>

<script>
  const alert = document.querySelector('ion-alert');

  alert.buttons = [
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Alert canceled');
      },
    },
    {
      text: 'OK',
      role: 'confirm',
      handler: () => {
        console.log('Alert confirmed');
      },
    },
  ];

  alert.addEventListener('ionAlertDidDismiss', (event) => {
    console.log(`Dismissed with role: ${event.detail.role}`);
  });
</script>

Angular

src/app/example.component.html

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert
  trigger="present-alert"
  header="Alert!"
  [buttons]="alertButtons"
  (didDismiss)="setResult($event)"
></ion-alert>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonAlert, IonButton } from '@ionic/angular';
import type { OverlayEventDetail } from '@ionic/core';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonAlert, IonButton],
})
export class ExampleComponent {
  public alertButtons = [
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Alert canceled');
      },
    },
    {
      text: 'OK',
      role: 'confirm',
      handler: () => {
        console.log('Alert confirmed');
      },
    },
  ];

  setResult(event: CustomEvent<OverlayEventDetail>) {
    console.log(`Dismissed with role: ${event.detail.role}`);
  }
}

React

import React from 'react';
import { IonAlert, IonButton } from '@ionic/react';

function Example() {
  return (
    <>
      <IonButton id="present-alert">Click Me</IonButton>
      <IonAlert
        header="Alert!"
        trigger="present-alert"
        buttons={[
          {
            text: 'Cancel',
            role: 'cancel',
            handler: () => {
              console.log('Alert canceled');
            },
          },
          {
            text: 'OK',
            role: 'confirm',
            handler: () => {
              console.log('Alert confirmed');
            },
          },
        ]}
        onDidDismiss={({ detail }) => console.log(`Dismissed with role: ${detail.role}`)}
      ></IonAlert>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button id="present-alert">Click Me</ion-button>
  <ion-alert
    trigger="present-alert"
    header="Alert!"
    :buttons="alertButtons"
    @didDismiss="logResult($event)"
  ></ion-alert>
</template>

<script setup lang="ts">
  import { IonAlert, IonButton } from '@ionic/vue';

  const alertButtons = [
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Alert canceled');
      },
    },
    {
      text: 'OK',
      role: 'confirm',
      handler: () => {
        console.log('Alert confirmed');
      },
    },
  ];

  const logResult = (event: CustomEvent) => {
    console.log(`Dismissed with role: ${event.detail.role}`);
  };
</script>

Console Console messages will appear here when logged from the example above.

Inputs

Alert는 앱으로 데이터를 다시 전달할 수 있는 여러 다양한 입력을 포함할 수도 있어요. 입력은 사용자에게 정보를 묻는 간단한 방법으로 사용할 수 있어요. Radio, checkbox, 텍스트 입력이 모두 지원되지만, 섞어 쓸 수는 없어요. 예를 들어 alert가 모든 radio 버튼 입력이거나 모든 checkbox 입력일 수는 있지만, 같은 alert에 radio와 checkbox 입력을 섞을 수는 없어요. 다만 url, email, text, textarea 등 서로 다른 유형의 "텍스트" 입력은 섞을 수 있다는 점에 유의하세요. alert의 지침에 맞지 않는 복잡한 폼 UI가 필요하다면 modal 안에서 폼을 만드는 것을 권장해요.

Text Inputs Example

JavaScript

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert trigger="present-alert" header="Please enter your info"></ion-alert>

<script>
  const alert = document.querySelector('ion-alert');

  alert.buttons = ['OK'];
  alert.inputs = [
    {
      placeholder: 'Name',
    },
    {
      placeholder: 'Nickname (max 8 characters)',
      attributes: {
        maxlength: 8,
      },
    },
    {
      type: 'number',
      placeholder: 'Age',
      min: 1,
      max: 100,
    },
    {
      type: 'textarea',
      placeholder: 'A little about yourself',
    },
  ];
</script>

Angular

src/app/example.component.html

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert
  trigger="present-alert"
  header="Please enter your info"
  [buttons]="alertButtons"
  [inputs]="alertInputs"
></ion-alert>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonAlert, IonButton } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonAlert, IonButton],
})
export class ExampleComponent {
  public alertButtons = ['OK'];
  public alertInputs = [
    {
      placeholder: 'Name',
    },
    {
      placeholder: 'Nickname (max 8 characters)',
      attributes: {
        maxlength: 8,
      },
    },
    {
      type: 'number',
      placeholder: 'Age',
      min: 1,
      max: 100,
    },
    {
      type: 'textarea',
      placeholder: 'A little about yourself',
    },
  ];
}

React

import React from 'react';
import { IonAlert, IonButton } from '@ionic/react';

function Example() {
  return (
    <>
      <IonButton id="present-alert">Click Me</IonButton>
      <IonAlert
        trigger="present-alert"
        header="Please enter your info"
        buttons={['OK']}
        inputs={[
          {
            placeholder: 'Name',
          },
          {
            placeholder: 'Nickname (max 8 characters)',
            attributes: {
              maxlength: 8,
            },
          },
          {
            type: 'number',
            placeholder: 'Age',
            min: 1,
            max: 100,
          },
          {
            type: 'textarea',
            placeholder: 'A little about yourself',
          },
        ]}
      ></IonAlert>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button id="present-alert">Click Me</ion-button>
  <ion-alert
    trigger="present-alert"
    header="Please enter your info"
    :buttons="alertButtons"
    :inputs="alertInputs"
  ></ion-alert>
</template>

<script setup lang="ts">
  import { IonAlert, IonButton } from '@ionic/vue';

  const alertButtons = ['OK'];
  const alertInputs = [
    {
      placeholder: 'Name',
    },
    {
      placeholder: 'Nickname (max 8 characters)',
      attributes: {
        maxlength: 8,
      },
    },
    {
      type: 'number',
      placeholder: 'Age',
      min: 1,
      max: 100,
    },
    {
      type: 'textarea',
      placeholder: 'A little about yourself',
    },
  ];
</script>

Radio Example

JavaScript

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert trigger="present-alert" header="Select your favorite color"></ion-alert>

<script>
  const alert = document.querySelector('ion-alert');

  alert.buttons = ['OK'];
  alert.inputs = [
    {
      label: 'Red',
      type: 'radio',
      value: 'red',
    },
    {
      label: 'Blue',
      type: 'radio',
      value: 'blue',
    },
    {
      label: 'Green',
      type: 'radio',
      value: 'green',
    },
  ];
</script>

Angular

src/app/example.component.html

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert
  trigger="present-alert"
  header="Select your favorite color"
  [buttons]="alertButtons"
  [inputs]="alertInputs"
></ion-alert>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonAlert, IonButton } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonAlert, IonButton],
})
export class ExampleComponent {
  public alertButtons = ['OK'];
  public alertInputs = [
    {
      label: 'Red',
      type: 'radio',
      value: 'red',
    },
    {
      label: 'Blue',
      type: 'radio',
      value: 'blue',
    },
    {
      label: 'Green',
      type: 'radio',
      value: 'green',
    },
  ];
}

React

import React from 'react';
import { IonAlert, IonButton } from '@ionic/react';

function Example() {
  return (
    <>
      <IonButton id="present-alert">Click Me</IonButton>
      <IonAlert
        trigger="present-alert"
        header="Select your favorite color"
        buttons={['OK']}
        inputs={[
          {
            label: 'Red',
            type: 'radio',
            value: 'red',
          },
          {
            label: 'Blue',
            type: 'radio',
            value: 'blue',
          },
          {
            label: 'Green',
            type: 'radio',
            value: 'green',
          },
        ]}
      ></IonAlert>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button id="present-alert">Click Me</ion-button>
  <ion-alert
    trigger="present-alert"
    header="Select your favorite color"
    :buttons="alertButtons"
    :inputs="alertInputs"
  ></ion-alert>
</template>

<script setup lang="ts">
  import { IonAlert, IonButton } from '@ionic/vue';

  const alertButtons = ['OK'];
  const alertInputs = [
    {
      label: 'Red',
      type: 'radio',
      value: 'red',
    },
    {
      label: 'Blue',
      type: 'radio',
      value: 'blue',
    },
    {
      label: 'Green',
      type: 'radio',
      value: 'green',
    },
  ];
</script>

Customization

Alert는 scoped 캡슐화를 사용해요. 즉 런타임에 각 스타일에 추가 클래스를 붙여 CSS를 자동으로 범위를 한정해요. scoped 셀렉터를 CSS로 덮어쓰려면 높은 특정성(specificity)을 가진 셀렉터가 필요해요.

create 메서드의 cssClass에 커스텀 클래스를 전달하고, 그 클래스를 사용해 호스트와 내부 요소에 커스텀 스타일을 추가하는 것을 권장해요. 이 프로퍼티는 공백으로 구분된 여러 클래스를 받을 수도 있어요.

/* DOES NOT WORK - not specific enough */
.alert-wrapper {
  background: #e5e5e5;
}

/* Works - pass "my-custom-class" in cssClass to increase specificity */
.my-custom-class .alert-wrapper {
  background: #e5e5e5;
}

정의된 CSS Custom Properties 중 어느 것이든 개별 요소를 타겟할 필요 없이 Alert를 스타일링하는 데 사용할 수 있어요.

.my-custom-class {
  --background: #e5e5e5;
}

JavaScript

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert trigger="present-alert" class="custom-alert" header="Are you sure?"></ion-alert>

<script>
  const alert = document.querySelector('ion-alert');

  alert.buttons = [
    {
      text: 'No',
      cssClass: 'alert-button-cancel',
    },
    {
      text: 'Yes',
      cssClass: 'alert-button-confirm',
    },
  ];
</script>

<style>
  ion-alert.custom-alert {
    --backdrop-opacity: 0.7;
  }

  .custom-alert .alert-button-group {
    padding: 8px;
  }

  button.alert-button.alert-button-confirm {
    background-color: var(--ion-color-success);
    color: var(--ion-color-success-contrast);
  }

  .md button.alert-button.alert-button-confirm {
    border-radius: 4px;
  }

  .ios .custom-alert button.alert-button {
    border: 0.55px solid rgba(var(--ion-text-color-rgb, 0, 0, 0), 0.2);
  }

  .ios button.alert-button.alert-button-cancel {
    border-right: 0;
    border-bottom-left-radius: 13px;
    border-top-left-radius: 13px;
  }

  .ios button.alert-button.alert-button-confirm {
    border-bottom-right-radius: 13px;
    border-top-right-radius: 13px;
  }
</style>

Angular

src/app/example.component.html

<ion-button id="present-alert">Click Me</ion-button>
<ion-alert trigger="present-alert" class="custom-alert" header="Are you sure?" [buttons]="alertButtons"></ion-alert>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonAlert, IonButton } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonAlert, IonButton],
})
export class ExampleComponent {
  public alertButtons = [
    {
      text: 'No',
      cssClass: 'alert-button-cancel',
    },
    {
      text: 'Yes',
      cssClass: 'alert-button-confirm',
    },
  ];
}

src/global.css

ion-alert.custom-alert {
  --backdrop-opacity: 0.7;
}

.custom-alert .alert-button-group {
  padding: 8px;
}

button.alert-button.alert-button-confirm {
  background-color: var(--ion-color-success);
  color: var(--ion-color-success-contrast);
}

.md button.alert-button.alert-button-confirm {
  border-radius: 4px;
}

.ios .custom-alert button.alert-button {
  border: 0.55px solid rgba(var(--ion-text-color-rgb, 0, 0, 0), 0.2);
}

.ios button.alert-button.alert-button-cancel {
  border-right: 0;
  border-bottom-left-radius: 13px;
  border-top-left-radius: 13px;
}

.ios button.alert-button.alert-button-confirm {
  border-bottom-right-radius: 13px;
  border-top-right-radius: 13px;
}

React

src/main.tsx

import React from 'react';
import { IonAlert, IonButton } from '@ionic/react';

import './main.css';

function Example() {
  return (
    <>
      <IonButton id="present-alert">Click Me</IonButton>
      <IonAlert
        trigger="present-alert"
        header="Are you sure?"
        className="custom-alert"
        buttons={[
          {
            text: 'No',
            cssClass: 'alert-button-cancel',
          },
          {
            text: 'Yes',
            cssClass: 'alert-button-confirm',
          },
        ]}
      ></IonAlert>
    </>
  );
}
export default Example;

src/main.css

ion-alert.custom-alert {
  --backdrop-opacity: 0.7;
}

.custom-alert .alert-button-group {
  padding: 8px;
}

button.alert-button.alert-button-confirm {
  background-color: var(--ion-color-success);
  color: var(--ion-color-success-contrast);
}

.md button.alert-button.alert-button-confirm {
  border-radius: 4px;
}

.ios .custom-alert button.alert-button {
  border: 0.55px solid rgba(var(--ion-text-color-rgb, 0, 0, 0), 0.2);
}

.ios button.alert-button.alert-button-cancel {
  border-right: 0;
  border-bottom-left-radius: 13px;
  border-top-left-radius: 13px;
}

.ios button.alert-button.alert-button-confirm {
  border-bottom-right-radius: 13px;
  border-top-right-radius: 13px;
}

Vue

<template>
  <ion-button id="present-alert">Click Me</ion-button>
  <ion-alert trigger="present-alert" class="custom-alert" header="Are you sure?" :buttons="alertButtons"></ion-alert>
</template>

<script setup lang="ts">
  import { IonAlert, IonButton } from '@ionic/vue';

  const alertButtons = [
    {
      text: 'No',
      cssClass: 'alert-button-cancel',
    },
    {
      text: 'Yes',
      cssClass: 'alert-button-confirm',
    },
  ];
</script>

<style>
  ion-alert.custom-alert {
    --backdrop-opacity: 0.7;
  }

  .custom-alert .alert-button-group {
    padding: 8px;
  }

  button.alert-button.alert-button-confirm {
    background-color: var(--ion-color-success);
    color: var(--ion-color-success-contrast);
  }

  .md button.alert-button.alert-button-confirm {
    border-radius: 4px;
  }

  .ios .custom-alert button.alert-button {
    border: 0.55px solid rgba(var(--ion-text-color-rgb, 0, 0, 0), 0.2);
  }

  .ios button.alert-button.alert-button-cancel {
    border-right: 0;
    border-bottom-left-radius: 13px;
    border-top-left-radius: 13px;
  }

  .ios button.alert-button.alert-button-confirm {
    border-bottom-right-radius: 13px;
    border-top-right-radius: 13px;
  }
</style>

Note

Ionic Angular 앱을 만들고 있다면 스타일을 전역 스타일시트 파일에 추가해야 해요.

Accessibility

Screen Readers

Alert는 스크린 리더가 접근할 수 있도록 aria 프로퍼티를 설정해요. 하지만 이 프로퍼티가 충분히 설명적이지 않거나 앱에서 사용되는 방식과 맞지 않으면 덮어쓸 수 있어요.

Role

Ionic은 입력이나 버튼이 포함되어 있으면 Alert의 role을 자동으로 alertdialog로, 없으면 alert로 설정해요.

Alert Description

Alert에 header 프로퍼티가 정의되어 있으면 aria-labelledby 속성이 자동으로 헤더의 ID로 설정돼요. header가 정의되지 않았다면 subHeader 요소가 대체(fallback)로 사용돼요. 마찬가지로 message 프로퍼티가 정의되어 있으면 aria-describedby 속성이 자동으로 message 요소의 ID로 설정돼요.

ARIA 스펙에 맞추려면 Alert에 message가 있고, header나 subHeader 중 하나는 있도록 하는 것을 강력히 권장해요. header나 subHeader를 포함하지 않기로 선택했다면 htmlAttributes 프로퍼티를 사용해 설명적인 aria-label을 제공하는 대안이 있어요.

Angular

const alert = await this.alertController.create({
  message: 'This is an alert with custom aria attributes.',
  htmlAttributes: {
    'aria-label': 'alert dialog',
  },
});

Javascript

const alert = await this.alertController.create({
  message: 'This is an alert with custom aria attributes.',
  htmlAttributes: {
    'aria-label': 'alert dialog',
  },
});

React

useIonAlert({
  message: 'This is an alert with custom aria attributes.',
  htmlAttributes: {
    'aria-label': 'alert dialog',
  },
});

Vue

const alert = await alertController.create({
  message: 'This is an alert with custom aria attributes.',
  htmlAttributes: {
    'aria-label': 'alert dialog',
  },
});

Alert의 htmlAttributes 프로퍼티에 커스텀 값을 정의하면 모든 ARIA 속성을 수동으로 덮어쓸 수 있어요.

Alert Buttons Description

텍스트가 포함된 버튼은 스크린 리더가 읽어 줘요. 기존 텍스트 외의 설명이 필요하다면 버튼의 htmlAttributes 프로퍼티에 aria-label을 전달해 버튼에 레이블을 설정할 수 있어요.

Angular

const alert = await this.alertController.create({
  header: 'Header',
  buttons: [
    {
      text: 'Exit',
      htmlAttributes: {
        'aria-label': 'close',
      },
    },
  ],
});

Javascript

const alert = await this.alertController.create({
  header: 'Header',
  buttons: [
    {
      text: 'Exit',
      htmlAttributes: {
        'aria-label': 'close',
      },
    },
  ],
});

React

useIonAlert({
  header: 'Header',
  buttons: [
    {
      text: 'Exit',
      htmlAttributes: {
        'aria-label': 'close',
      },
    },
  ],
});

Vue

const alert = await alertController.create({
  header: 'Header',
  buttons: [
    {
      text: 'Exit',
      htmlAttributes: {
        'aria-label': 'close',
      },
    },
  ],
});

Interfaces

AlertButton

type AlertButtonOverlayHandler = boolean | void | { [key: string]: any };

interface AlertButton {
  text: string;
  role?: 'cancel' | 'destructive' | string;
  cssClass?: string | string[];
  id?: string;
  htmlAttributes?: { [key: string]: any };
  handler?: (value: any) => AlertButtonOverlayHandler | Promise<AlertButtonOverlayHandler>;
}

AlertInput

interface AlertInput {
  type?: TextFieldTypes | 'checkbox' | 'radio' | 'textarea';
  name?: string;
  placeholder?: string;
  value?: any;
  /**
   * The label text to display next to the input, if the input type is `radio` or `checkbox`.
   */
  label?: string;
  checked?: boolean;
  disabled?: boolean;
  id?: string;
  handler?: (input: AlertInput) => void;
  min?: string | number;
  max?: string | number;
  cssClass?: string | string[];
  attributes?: { [key: string]: any };
  tabindex?: number;
}

AlertOptions

interface AlertOptions {
  header?: string;
  subHeader?: string;
  message?: string | IonicSafeString;
  cssClass?: string | string[];
  inputs?: AlertInput[];
  buttons?: (AlertButton | string)[];
  backdropDismiss?: boolean;
  translucent?: boolean;
  animated?: boolean;
  htmlAttributes?: { [key: string]: any };

  mode?: Mode;
  keyboardClose?: boolean;
  id?: string;

  enterAnimation?: AnimationBuilder;
  leaveAnimation?: AnimationBuilder;
}

Properties

animated

Description: If true, the alert will animate.

Attribute: animated

Type: boolean

Default: true

backdropDismiss

Description: If true, the alert will be dismissed when the backdrop is clicked.

Attribute: backdrop-dismiss

Type: boolean

Default: true

buttons

Description: Array of buttons to be added to the alert.

Attribute: undefined

Type: (string | AlertButton)[]

Default: []

cssClass

Description: Additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces.

Attribute: css-class

Type: string | string[] | undefined

Default: undefined

enterAnimation

Description: Animation to use when the alert is presented.

Attribute: undefined

Type: ((baseEl: any, opts?: any) => Animation) | undefined

Default: undefined

Description: The main title in the heading of the alert.

Attribute: header

Type: string | undefined

Default: undefined

htmlAttributes

Description: Additional attributes to pass to the alert.

Attribute: undefined

Type: undefined | { [key: string]: any; }

Default: undefined

inputs

Description: Array of input to show in the alert.

Attribute: undefined

Type: AlertInput[]

Default: []

isOpen

Description: If true, the alert will open. If false, the alert will close. Use this if you need finer grained control over presentation, otherwise just use the alertController or the trigger property. Note: isOpen will not automatically be set back to false when the alert dismisses. You will need to do that in your code.

Attribute: is-open

Type: boolean

Default: false

keyboardClose

Description: If true, the keyboard will be automatically dismissed when the overlay is presented.

Attribute: keyboard-close

Type: boolean

Default: true

leaveAnimation

Description: Animation to use when the alert is dismissed.

Attribute: undefined

Type: ((baseEl: any, opts?: any) => Animation) | undefined

Default: undefined

message

Description: 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. For example <Ionic> would become &lt;Ionic&gt; For more information: Security Documentation This property accepts custom HTML as a string. Content is parsed as plaintext by default. innerHTMLTemplatesEnabled must be set to true in the Ionic config before custom HTML can be used.

Attribute: message

Type: IonicSafeString | string | undefined

Default: undefined

mode

Description: The mode determines which platform styles to use. This is a virtual property that is set once during initialization and will not update if you change its value after the initial render.

Attribute: mode

Type: "ios" | "md"

Default: undefined

subHeader

Description: The subtitle in the heading of the alert. Displayed under the title.

Attribute: sub-header

Type: string | undefined

Default: undefined

translucent

Description: If true, the alert will be translucent. Only applies when the mode is "ios" and the device supports backdrop-filter.

Attribute: translucent

Type: boolean

Default: false

trigger

Description: An ID corresponding to the trigger element that causes the alert to open when clicked.

Attribute: trigger

Type: string | undefined

Default: undefined

Events

Name Description Bubbles
didDismiss Emitted after the alert has dismissed. Shorthand for ionAlertDidDismiss. true
didPresent Emitted after the alert has presented. Shorthand for ionAlertWillDismiss. true
ionAlertDidDismiss Emitted after the alert has dismissed. true
ionAlertDidPresent Emitted after the alert has presented. true
ionAlertWillDismiss Emitted before the alert has dismissed. true
ionAlertWillPresent Emitted before the alert has presented. true
willDismiss Emitted before the alert has dismissed. Shorthand for ionAlertWillDismiss. true
willPresent Emitted before the alert has presented. Shorthand for ionAlertWillPresent. true

Methods

dismiss

Description: Dismiss the alert overlay after it has been presented. This is a no-op if the overlay has not been presented yet. If you want to remove an overlay from the DOM that was never presented, use the remove method.

Signature: dismiss(data?: any, role?: string) => Promise<boolean>

Parameters: data: Any data to emit in the dismiss events. role: The role of the element that is dismissing the alert. This can be useful in a button handler for determining which button was clicked to dismiss the alert. Some examples include: "cancel", "destructive", "selected", and "backdrop".

onDidDismiss

Description: Returns a promise that resolves when the alert did dismiss.

Signature: onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>

onWillDismiss

Description: Returns a promise that resolves when the alert will dismiss.

Signature: onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>

present

Description: Present the alert overlay after it has been created.

Signature: present() => Promise<void>

CSS Shadow Parts

No CSS shadow parts available for this component.

CSS Custom Properties

iOS

Name Description
--backdrop-opacity Opacity of the backdrop
--background Background of the alert
--height Height of the alert
--max-height Maximum height of the alert
--max-width Maximum width of the alert
--min-height Minimum height of the alert
--min-width Minimum width of the alert
--width Width of the alert

MD

Name Description
--backdrop-opacity Opacity of the backdrop
--background Background of the alert
--height Height of the alert
--max-height Maximum height of the alert
--max-width Maximum width of the alert
--min-height Minimum height of the alert
--min-width Minimum width of the alert
--width Width of the alert

Slots

No slots available for this component.

더 알아보기 (Learn more)

ion-alert는 정보를 보여 주거나 입력을 받는 데 사용하는 다이얼로그예요. 템플릿에 넣고 trigger나 isOpen으로 표시하거나, alertController로 제어할 수 있어요. 버튼(role, handler), 입력(inputs), 접근성(aria 속성) 설정을 상황에 맞게 활용해 보세요.