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

ion-toast

원문 보기 위키 갱신

ion-toast은 현대적인 애플리케이션에서 흔히 사용되는 미묘한 알림이에요. 작업에 대한 피드백을 제공하거나 시스템 메시지를 표시하는 데 쓰이고, 앱 콘텐츠 위에 나타나며 앱에 의해 닫아 사용자 상호작용을 재개할 수 있어요. 이 글에서 인라인 토스트, 컨트롤러 토스트, 닫기, 위치, 스와이프 닫기, 레이아웃, 아이콘, 테마, 접근성을 살펴볼게요.

출처: 문서

본문

Encapsulation: shadow

Toast는 현대적인 애플리케이션에서 흔히 사용되는 미묘한 알림입니다. 작업에 대한 피드백을 제공하거나 시스템 메시지를 표시하는 데 사용할 수 있습니다. Toast는 앱의 콘텐츠 위에 나타나며, 앱에 의해 닫혀 사용자와 앱의 상호작용을 재개할 수 있습니다.

인라인 토스트 (권장)

ion-toast는 템플릿에 컴포넌트를 직접 작성해 사용할 수 있습니다. 이렇게 하면 토스트를 표시하기 위해 연결해야 하는 핸들러의 수가 줄어듭니다.

JavaScript

<ion-header>
  <ion-toolbar>
    <ion-title>Inline Toast</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
  <ion-button id="open-toast" expand="block">Open</ion-button>
  <p id="message">This toast example uses triggers to automatically open a toast when the button is clicked.</p>
  <ion-toast trigger="open-toast" message="This toast will disappear after 5 seconds" duration="5000"></ion-toast>
</ion-content>

Angular

src/app/example.component.html

<ion-header>
  <ion-toolbar>
    <ion-title>Inline Toast</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
  <ion-button id="open-toast" expand="block">Open</ion-button>
  <p id="message">This toast example uses triggers to automatically open a toast when the button is clicked.</p>
  <ion-toast trigger="open-toast" message="This toast will disappear after 5 seconds" [duration]="5000"></ion-toast>
</ion-content>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonButton, IonContent, IonHeader, IonTitle, IonToast, IonToolbar } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonContent, IonHeader, IonTitle, IonToast, IonToolbar],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonButton, IonHeader, IonContent, IonToolbar, IonTitle, IonPage, IonToast } from '@ionic/react';

function Example() {
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Inline Toast</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent className="ion-padding">
        <IonButton id="open-toast" expand="block">
          Open
        </IonButton>
        <p>This toast example uses triggers to automatically open a toast when the button is clicked.</p>
        <IonToast trigger="open-toast" message="This toast will disappear after 5 seconds" duration={5000}></IonToast>
      </IonContent>
    </IonPage>
  );
}

export default Example;

Vue

<template>
  <ion-header>
    <ion-toolbar>
      <ion-title>Inline Toast</ion-title>
    </ion-toolbar>
  </ion-header>
  <ion-content class="ion-padding">
    <ion-button id="open-toast" expand="block">Open</ion-button>
    <p>This toast example uses triggers to automatically open a toast when the button is clicked.</p>
    <ion-toast trigger="open-toast" message="This toast will disappear after 5 seconds" :duration="5000"></ion-toast>
  </ion-content>
</template>

<script setup lang="ts">
  import { IonButton, IonHeader, IonContent, IonToolbar, IonTitle, IonToast } from '@ionic/vue';
</script>

isOpen 사용하기

ion-toast의 isOpen 속성은 개발자가 앱 상태에서 토스트의 표시 상태를 제어할 수 있게 합니다. 즉 isOpen이 true로 설정되면 토스트가 표시되고, false로 설정되면 토스트가 닫힙니다.

isOpen은 단방향 데이터 바인딩을 사용하므로, 토스트가 닫혔을 때 자동으로 false로 설정되지 않습니다. 개발자는 ionToastDidDismiss 또는 didDismiss 이벤트를 수신하고 isOpen을 false로 설정해야 합니다. 그 이유는 이것이 ion-toast의 내부가 애플리케이션 상태와 강하게 결합되는 것을 방지하기 때문입니다. 단방향 데이터 바인딩을 사용하면 토스트는 반응형 변수가 제공하는 boolean 값만 신경 쓰면 됩니다. 양방향 데이터 바인딩을 사용하면 토스트는 boolean 값뿐 아니라 반응형 변수 자체의 존재까지 신경 써야 합니다. 이는 비결정적인 동작을 일으키고 애플리케이션을 디버깅하기 어렵게 만들 수 있습니다.

JavaScript

<ion-header>
  <ion-toolbar>
    <ion-title>Inline Toast</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
  <ion-button expand="block" onclick="toast.isOpen = true">Open</ion-button>
  <ion-toast duration="5000" message="This toast will close in 5 seconds"></ion-toast>
</ion-content>

<script>
  var toast = document.querySelector('ion-toast');
  toast.addEventListener('didDismiss', () => {
    toast.isOpen = false;
  });
</script>

Angular

src/app/example.component.html

<ion-header>
  <ion-toolbar>
    <ion-title>Inline Toast</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
  <ion-button expand="block" (click)="setOpen(true)">Open</ion-button>
  <ion-toast
    [isOpen]="isToastOpen"
    message="This toast will close in 5 seconds"
    [duration]="5000"
    (didDismiss)="setOpen(false)"
  ></ion-toast>
</ion-content>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonButton, IonContent, IonHeader, IonTitle, IonToast, IonToolbar } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonContent, IonHeader, IonTitle, IonToast, IonToolbar],
})
export class ExampleComponent {
  isToastOpen = false;

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

React

import React, { useState } from 'react';
import { IonButton, IonHeader, IonContent, IonToolbar, IonTitle, IonPage, IonToast } from '@ionic/react';

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

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Inline Toast</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent className="ion-padding">
        <IonButton expand="block" onClick={() => setIsOpen(true)}>
          Open
        </IonButton>
        <IonToast
          isOpen={isOpen}
          message="This toast will close in 5 seconds"
          onDidDismiss={() => setIsOpen(false)}
          duration={5000}
        ></IonToast>
      </IonContent>
    </IonPage>
  );
}

export default Example;

Vue

<template>
  <ion-header>
    <ion-toolbar>
      <ion-title>Inline Toast</ion-title>
    </ion-toolbar>
  </ion-header>
  <ion-content class="ion-padding">
    <ion-button expand="block" @click="setOpen(true)">Open</ion-button>
    <ion-toast
      :is-open="isOpen"
      message="This toast will close in 5 seconds"
      :duration="5000"
      @didDismiss="setOpen(false)"
    ></ion-toast>
  </ion-content>
</template>

<script setup lang="ts">
  import { IonButton, IonHeader, IonToolbar, IonContent, IonTitle, IonToast } from '@ionic/vue';
  import { ref } from 'vue';

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

컨트롤러 토스트

JavaScript

<ion-button expand="block" onclick="presentToast('top')">Present Toast At the Top</ion-button>
<ion-button expand="block" onclick="presentToast('middle')">Present Toast At the Middle</ion-button>
<ion-button expand="block" onclick="presentToast('bottom')">Present Toast At the Bottom</ion-button>

<script>
  async function presentToast(position) {
    const toast = await this.toastController.create({
      message: 'Hello World!',
      duration: 1500,
      position: position,
    });

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

Angular

src/app/example.component.html

<ion-button expand="block" (click)="presentToast('top')">Present Toast At the Top</ion-button>
<ion-button expand="block" (click)="presentToast('middle')">Present Toast At the Middle</ion-button>
<ion-button expand="block" (click)="presentToast('bottom')">Present Toast At the Bottom</ion-button>

src/app/example.component.ts

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

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

  async presentToast(position: 'top' | 'middle' | 'bottom') {
    const toast = await this.toastController.create({
      message: 'Hello World!',
      duration: 1500,
      position: position,
    });

    await toast.present();
  }
}

React

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

function Example() {
  const [present] = useIonToast();

  const presentToast = (position: 'top' | 'middle' | 'bottom') => {
    present({
      message: 'Hello World!',
      duration: 1500,
      position: position,
    });
  };

  return (
    <>
      <IonButton expand="block" onClick={() => presentToast('top')}>
        Present Toast At the Top
      </IonButton>
      <IonButton expand="block" onClick={() => presentToast('middle')}>
        Present Toast At the Middle
      </IonButton>
      <IonButton expand="block" onClick={() => presentToast('bottom')}>
        Present Toast At the Bottom
      </IonButton>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button expand="block" @click="presentToast('top')">Present Toast At the Top</ion-button>
  <ion-button expand="block" @click="presentToast('middle')">Present Toast At the Middle</ion-button>
  <ion-button expand="block" @click="presentToast('bottom')">Present Toast At the Bottom</ion-button>
</template>

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

  const presentToast = async (position: 'top' | 'middle' | 'bottom') => {
    const toast = await toastController.create({
      message: 'Hello World!',
      duration: 1500,
      position: position,
    });

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

닫기 (Dismissing)

Toast는 미묘한 알림으로 의도되었으며 사용자를 방해해서는 안 됩니다. 그 결과 토스트를 닫는 데 사용자 상호작용이 요구되어서는 안 됩니다.

토스트 옵션의 duration에 표시할 밀리초 수를 전달하면 특정 시간 후에 토스트가 자동으로 닫힙니다. "cancel" 역할의 버튼이 추가되면 그 버튼이 토스트를 닫습니다. 생성 후 토스트를 닫으려면 인스턴스에서 dismiss() 메서드를 호출하세요.

하드웨어 뒤로 가기 버튼을 누르는 것은 사용자를 방해해서는 안 되므로 토스트를 닫지 않습니다.

다음 예제는 buttons 속성을 사용해 클릭 시 토스트를 자동으로 닫는 버튼을 추가하는 방법과, 닫힘 이벤트의 role을 수집하는 방법을 보여줍니다.

JavaScript

<ion-button id="open-toast">Open Toast</ion-button>
<ion-toast trigger="open-toast" duration="3000" message="Hello World!"></ion-toast>

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

  toast.buttons = [
    {
      text: 'More Info',
      role: 'info',
      handler: () => {
        console.log('More Info clicked');
      },
    },
    {
      text: 'Dismiss',
      role: 'cancel',
      handler: () => {
        console.log('Dismiss clicked');
      },
    },
  ];

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

Angular

src/app/example.component.html

<ion-button id="open-toast">Open Toast</ion-button>
<ion-toast
  trigger="open-toast"
  message="Hello World!"
  [duration]="3000"
  [buttons]="toastButtons"
  (didDismiss)="setRoleMessage($event)"
></ion-toast>

src/app/example.component.ts

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

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonToast],
})
export class ExampleComponent {
  public toastButtons = [
    {
      text: 'More Info',
      role: 'info',
      handler: () => {
        console.log('More Info clicked');
      },
    },
    {
      text: 'Dismiss',
      role: 'cancel',
      handler: () => {
        console.log('Dismiss clicked');
      },
    },
  ];

  setRoleMessage(event: CustomEvent) {
    const { role } = event.detail;
    console.log(`Dismissed with role: ${role}`);
  }
}

React

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

function Example() {
  return (
    <>
      <IonButton id="open-toast">Open Toast</IonButton>
      <IonToast
        trigger="open-toast"
        message="Hello World!"
        duration={3000}
        buttons={[
          {
            text: 'More Info',
            role: 'info',
            handler: () => {
              console.log('More Info clicked');
            },
          },
          {
            text: 'Dismiss',
            role: 'cancel',
            handler: () => {
              console.log('Dismiss clicked');
            },
          },
        ]}
        onDidDismiss={(e: CustomEvent) => console.log(`Dismissed with role: ${e.detail.role}`)}
      ></IonToast>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button id="open-toast">Open Toast</ion-button>
  <ion-toast
    trigger="open-toast"
    message="Hello World!"
    :duration="3000"
    :buttons="toastButtons"
    @didDismiss="handleDismiss($event)"
  ></ion-toast>
</template>

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

  const toastButtons = [
    {
      text: 'More Info',
      role: 'info',
      handler: () => {
        console.log('More Info clicked');
      },
    },
    {
      text: 'Dismiss',
      role: 'cancel',
      handler: () => {
        console.log('Dismiss clicked');
      },
    },
  ];

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

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

위치 지정

Toast는 뷰포트의 상단, 하단 또는 중간에 배치할 수 있습니다. 위치는 생성할 때 전달할 수 있습니다. 가능한 값은 top, bottom, middle입니다. 위치를 지정하지 않으면 토스트는 뷰포트 하단에 표시됩니다.

상대 위치 지정

헤더, 푸터 또는 FAB 같은 내비게이션 요소와 함께 토스트를 표시하면 기본적으로 토스트가 이러한 요소와 겹칠 수 있습니다. 이는 요소 참조 또는 ID를 취하는 positionAnchor 속성으로 해결할 수 있습니다. 토스트는 선택한 요소에 상대적으로 배치되며, position="top"을 사용하면 요소 아래에, position="bottom"을 사용하면 요소 위에 나타납니다. position="middle"을 사용하면 positionAnchor 속성은 무시됩니다.

JavaScript

<ion-header id="header">
  <ion-toolbar>
    <ion-title>Header</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-button id="headerAnchor">Anchor to Header</ion-button>
  <ion-button id="footerAnchor">Anchor to Footer</ion-button>

  <ion-toast
    trigger="headerAnchor"
    position="top"
    position-anchor="header"
    message="Hello World!"
    duration="2000"
  ></ion-toast>
  <ion-toast
    trigger="footerAnchor"
    position="bottom"
    position-anchor="footer"
    message="Hello World!"
    duration="2000"
  ></ion-toast>
</ion-content>

<ion-footer id="footer">
  <ion-toolbar>
    <ion-title>Footer</ion-title>
  </ion-toolbar>
</ion-footer>

Angular

src/app/example.component.html

<ion-header id="header">
  <ion-toolbar>
    <ion-title>Header</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-button id="headerAnchor">Anchor to Header</ion-button>
  <ion-button id="footerAnchor">Anchor to Footer</ion-button>

  <ion-toast
    trigger="headerAnchor"
    position="top"
    positionAnchor="header"
    message="Hello World!"
    duration="2000"
  ></ion-toast>
  <ion-toast
    trigger="footerAnchor"
    position="bottom"
    positionAnchor="footer"
    message="Hello World!"
    duration="2000"
  ></ion-toast>
</ion-content>

<ion-footer id="footer">
  <ion-toolbar>
    <ion-title>Footer</ion-title>
  </ion-toolbar>
</ion-footer>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonButton, IonContent, IonFooter, IonHeader, IonTitle, IonToast, IonToolbar } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonContent, IonFooter, IonHeader, IonTitle, IonToast, IonToolbar],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonButton, IonContent, IonFooter, IonHeader, IonTitle, IonToast, IonToolbar } from '@ionic/react';

function Example() {
  return (
    <>
      <IonHeader id="header">
        <IonToolbar>
          <IonTitle>Header</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent className="ion-padding">
        <IonButton id="headerAnchor">Anchor to Header</IonButton>
        <IonButton id="footerAnchor">Anchor to Footer</IonButton>

        <IonToast
          trigger="headerAnchor"
          position="top"
          positionAnchor="header"
          message="Hello World!"
          duration={2000}
        ></IonToast>
        <IonToast
          trigger="footerAnchor"
          position="bottom"
          positionAnchor="footer"
          message="Hello World!"
          duration={2000}
        ></IonToast>
      </IonContent>

      <IonFooter id="footer">
        <IonToolbar>
          <IonTitle>Footer</IonTitle>
        </IonToolbar>
      </IonFooter>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-header id="header">
    <ion-toolbar>
      <ion-title>Header</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content class="ion-padding">
    <ion-button id="headerAnchor">Anchor to Header</ion-button>
    <ion-button id="footerAnchor">Anchor to Footer</ion-button>

    <ion-toast
      trigger="headerAnchor"
      position="top"
      position-anchor="header"
      message="Hello World!"
      :duration="2000"
    ></ion-toast>
    <ion-toast
      trigger="footerAnchor"
      position="bottom"
      position-anchor="footer"
      message="Hello World!"
      :duration="2000"
    ></ion-toast>
  </ion-content>

  <ion-footer id="footer">
    <ion-toolbar>
      <ion-title>Footer</ion-title>
    </ion-toolbar>
  </ion-footer>
</template>

<script setup lang="ts">
  import { IonButton, IonContent, IonFooter, IonHeader, IonTitle, IonToast, IonToolbar } from '@ionic/vue';
</script>

스와이프로 닫기

swipeGesture 속성을 사용하면 Toast를 스와이프해 닫을 수 있습니다. 이 기능은 위치를 인식하는데, 즉 사용자가 스와이프해야 하는 방향이 position 속성의 값에 따라 달라집니다. 추가로 사용자가 스와이프해야 하는 거리는 positionAnchor 속성의 영향을 받을 수 있습니다.

JavaScript

<ion-content class="ion-padding">
  <ion-button id="open-toast">Open Toast</ion-button>
  <ion-toast
    message="This toast can be swiped to dismiss"
    trigger="open-toast"
    swipe-gesture="vertical"
    position="bottom"
    position-anchor="footer"
  ></ion-toast>
</ion-content>
<ion-footer id="footer">
  <ion-toolbar>
    <ion-title>Footer</ion-title>
  </ion-toolbar>
</ion-footer>

Angular

src/app/example.component.html

<ion-content class="ion-padding">
  <ion-button id="open-toast">Open Toast</ion-button>
  <ion-toast
    message="This toast can be swiped to dismiss"
    trigger="open-toast"
    swipeGesture="vertical"
    position="bottom"
    positionAnchor="footer"
  ></ion-toast>
</ion-content>
<ion-footer id="footer">
  <ion-toolbar>
    <ion-title>Footer</ion-title>
  </ion-toolbar>
</ion-footer>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonButton, IonContent, IonFooter, IonTitle, IonToast, IonToolbar } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonContent, IonFooter, IonTitle, IonToast, IonToolbar],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonButton, IonContent, IonFooter, IonTitle, IonToast, IonToolbar } from '@ionic/react';

function Example() {
  return (
    <>
      <IonContent className="ion-padding">
        <IonButton id="open-toast">Open Toast</IonButton>
        <IonToast
          message="This toast can be swiped to dismiss"
          trigger="open-toast"
          swipeGesture="vertical"
          position="bottom"
          positionAnchor="footer"
        ></IonToast>
      </IonContent>
      <IonFooter id="footer">
        <IonToolbar>
          <IonTitle>Footer</IonTitle>
        </IonToolbar>
      </IonFooter>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-content class="ion-padding">
    <ion-button id="open-toast">Open Toast</ion-button>
    <ion-toast
      message="This toast can be swiped to dismiss"
      trigger="open-toast"
      swipe-gesture="vertical"
      position="bottom"
      position-anchor="footer"
    ></ion-toast>
  </ion-content>
  <ion-footer id="footer">
    <ion-toolbar>
      <ion-title>Footer</ion-title>
    </ion-toolbar>
  </ion-footer>
</template>

<script setup lang="ts">
  import { IonButton, IonContent, IonFooter, IonTitle, IonToast, IonToolbar } from '@ionic/vue';
</script>

레이아웃

토스트 안의 버튼 컨테이너는 layout 속성을 사용해 메시지와 같은 줄에 표시하거나 별도의 줄에 쌓아(stacked) 표시할 수 있습니다. Stacked 레이아웃은 긴 텍스트 값이 있는 버튼에 사용해야 합니다. 추가로 stacked 토스트 레이아웃의 버튼은 start 또는 end 중 하나의 side 값을 사용할 수 있지만, 둘 다 사용할 수는 없습니다.

JavaScript

<ion-button id="open-inline-toast">Open Baseline Layout Toast</ion-button>
<ion-button id="open-stacked-toast">Open Stacked Layout Toast</ion-button>
<ion-toast
  trigger="open-inline-toast"
  duration="3000"
  message="This is a toast with a long message and a button that appears on the same line."
></ion-toast>
<ion-toast
  trigger="open-stacked-toast"
  duration="3000"
  message="This is a toast with a long message and a button that appears on the next line."
  layout="stacked"
></ion-toast>

<script>
  const toasts = document.querySelectorAll('ion-toast');

  toasts.forEach((toast) => {
    toast.buttons = [
      {
        text: 'Action With Long Text',
      },
    ];
  });
</script>

Angular

src/app/example.component.html

<ion-button id="open-inline-toast">Open Baseline Layout Toast</ion-button>
<ion-button id="open-stacked-toast">Open Stacked Layout Toast</ion-button>
<ion-toast
  trigger="open-inline-toast"
  [duration]="3000"
  [buttons]="toastButtons"
  message="This is a toast with a long message and a button that appears on the same line."
></ion-toast>
<ion-toast
  trigger="open-stacked-toast"
  [duration]="3000"
  [buttons]="toastButtons"
  message="This is a toast with a long message and a button that appears on the next line."
  layout="stacked"
></ion-toast>

src/app/example.component.ts

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

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonToast],
})
export class ExampleComponent {
  toastButtons = [
    {
      text: 'Action With Long Text',
    },
  ];
}

React

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

function Example() {
  return (
    <>
      <IonButton id="open-stacked-toast">Open Stacked Layout Toast</IonButton>
      <IonButton id="open-inline-toast">Open Baseline Layout Toast</IonButton>
      <IonToast
        trigger="open-inline-toast"
        message="This is a toast with a long message and a button that appears on the same line."
        duration={3000}
        buttons={[
          {
            text: 'Action With Long Text',
          },
        ]}
      ></IonToast>
      <IonToast
        trigger="open-stacked-toast"
        message="This is a toast with a long message and a button that appears on the next line."
        duration={3000}
        buttons={[
          {
            text: 'Action With Long Text',
          },
        ]}
        layout="stacked"
      ></IonToast>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button id="open-inline-toast">Open Baseline Layout Toast</ion-button>
  <ion-button id="open-stacked-toast">Open Stacked Layout Toast</ion-button>
  <ion-toast
    trigger="open-inline-toast"
    :duration="3000"
    :buttons="toastButtons"
    message="This is a toast with a long message and a button that appears on the same line."
  ></ion-toast>
  <ion-toast
    trigger="open-stacked-toast"
    :duration="3000"
    :buttons="toastButtons"
    message="This is a toast with a long message and a button that appears on the next line."
    layout="stacked"
  ></ion-toast>
</template>

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

  const toastButtons = [
    {
      text: 'Action With Long Text',
    },
  ];
</script>

아이콘

토스트 안의 콘텐츠 옆에 아이콘을 추가할 수 있습니다. 일반적으로 토스트의 아이콘은 추가 스타일이나 맥락을 제공하는 데 사용해야 하며, 사용자의 주의를 끌거나 토스트의 우선순위를 높이는 데 사용해서는 안 됩니다. 사용자에게 더 높은 우선순위의 메시지를 전달하거나 응답을 보장하고 싶다면 Alert를 사용할 것을 권장합니다.

JavaScript

<ion-button id="open-toast">Open Toast</ion-button>
<ion-toast trigger="open-toast" message="Hello World!" duration="3000" icon="globe"></ion-toast>

Angular

src/app/example.component.html

<ion-button id="open-toast">Open Toast</ion-button>
<ion-toast trigger="open-toast" message="Hello World!" [duration]="3000" icon="globe"></ion-toast>

src/app/example.component.ts

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

import { addIcons } from 'ionicons';
import { globe } from 'ionicons/icons';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonToast],
})
export class ExampleComponent {
  constructor() {
    /**
     * Any icons you want to use in your application
     * can be registered in app.component.ts and then
     * referenced by name anywhere in your application.
     */
    addIcons({ globe });
  }
}

React

import React from 'react';
import { IonButton, IonToast } from '@ionic/react';
import { globe } from 'ionicons/icons';

function Example() {
  return (
    <>
      <IonButton id="open-toast">Open Toast</IonButton>
      <IonToast trigger="open-toast" message="Hello World!" duration={3000} icon={globe}></IonToast>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-button id="open-toast">Open Toast</ion-button>
  <ion-toast trigger="open-toast" message="Hello World!" :duration="3000" :icon="globe"></ion-toast>
</template>

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

테마 적용

JavaScript

<ion-button id="open-toast">Open Toast</ion-button>
<ion-toast trigger="open-toast" duration="3000" message="Hello Styled World!" class="custom-toast"></ion-toast>

<script>
  const toast = document.querySelector('ion-toast');
  toast.buttons = [
    {
      text: 'Dismiss',
      role: 'cancel',
    },
  ];
</script>

<style>
  ion-toast.custom-toast {
    --background: #f4f4fa;
    --box-shadow: 3px 3px 10px 0 rgba(0, 0, 0, 0.2);
    --color: #4b4a50;
  }

  ion-toast.custom-toast::part(message) {
    font-style: italic;
  }

  ion-toast.custom-toast::part(button) {
    border-left: 1px solid #d2d2d2;
    color: #030207;
    font-size: 15px;
  }
</style>

Angular

src/app/example.component.html

<ion-button id="open-toast">Open Toast</ion-button>
<ion-toast
  trigger="open-toast"
  [duration]="3000"
  message="Hello Styled World!"
  class="custom-toast"
  [buttons]="toastButtons"
></ion-toast>

src/app/example.component.ts

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

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonToast],
})
export class ExampleComponent {
  public toastButtons = [
    {
      text: 'Dismiss',
      role: 'cancel',
    },
  ];

  constructor() {}
}

src/global.css

ion-toast.custom-toast {
  --background: #f4f4fa;
  --box-shadow: 3px 3px 10px 0 rgba(0, 0, 0, 0.2);
  --color: #4b4a50;
}

ion-toast.custom-toast::part(message) {
  font-style: italic;
}

ion-toast.custom-toast::part(button) {
  border-left: 1px solid #d2d2d2;
  color: #030207;
  font-size: 15px;
}

React

src/main.tsx

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

import './main.css';

function Example() {
  return (
    <>
      <IonButton id="open-toast">Open Toast</IonButton>
      <IonToast
        trigger="open-toast"
        duration={3000}
        message="Hello Styled World!"
        className="custom-toast"
        buttons={[
          {
            text: 'Dismiss',
            role: 'cancel',
          },
        ]}
      ></IonToast>
    </>
  );
}
export default Example;

src/main.css

ion-toast.custom-toast {
  --background: #f4f4fa;
  --box-shadow: 3px 3px 10px 0 rgba(0, 0, 0, 0.2);
  --color: #4b4a50;
}

ion-toast.custom-toast::part(message) {
  font-style: italic;
}

ion-toast.custom-toast::part(button) {
  border-left: 1px solid #d2d2d2;
  color: #030207;
  font-size: 15px;
}

Vue

<template>
  <ion-button id="open-toast">Open Toast</ion-button>
  <ion-toast
    trigger="open-toast"
    :duration="3000"
    message="Hello Styled World!"
    class="custom-toast"
    :buttons="toastButtons"
  ></ion-toast>
</template>

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

  const toastButtons = [
    {
      text: 'Dismiss',
      role: 'cancel',
    },
  ];
</script>

<style>
  ion-toast.custom-toast {
    --background: #f4f4fa;
    --box-shadow: 3px 3px 10px 0 rgba(0, 0, 0, 0.2);
    --color: #4b4a50;
  }

  ion-toast.custom-toast::part(message) {
    font-style: italic;
  }

  ion-toast.custom-toast::part(button) {
    border-left: 1px solid #d2d2d2;
    color: #030207;
    font-size: 15px;
  }
</style>

접근성

포커스 관리

Toast는 미묘한 알림으로 의도되었으며 사용자를 방해해서는 안 됩니다. 토스트를 닫는 데 사용자 상호작용이 요구되어서는 안 됩니다. 그 결과 토스트가 표시될 때 포커스가 자동으로 토스트로 이동하지 않습니다.

스크린 리더

Toast는 screen readers에 접근 가능하도록 aria 속성을 설정하지만, 이러한 속성이 충분히 설명적이지 않거나 앱에서 토스트가 사용되는 방식과 일치하지 않으면 재정의할 수 있습니다.

역할 (Role)

ion-toast는 내부의 .toast-content 요소에 role="status"와 aria-live="polite"를 설정합니다. 이는 스크린 리더가 토스트 메시지와 헤더만 안내하게 합니다. 토스트가 표시될 때 버튼과 아이콘은 안내되지 않습니다.

aria-live는 토스트가 업데이트될 때 스크린 리더가 토스트의 콘텐츠를 안내하게 합니다. 그러나 속성이 'polite'로 설정되었으므로, 스크린 리더는 현재 작업을 방해해서는 안 됩니다.

Toast는 미묘한 알림으로 의도되었으므로 aria-live를 "assertive"로 설정해서는 안 됩니다. 개발자가 중요한 메시지로 사용자를 방해해야 한다면 alert를 사용할 것을 권장합니다.

토스트 버튼 설명

텍스트를 포함한 버튼은 상호작용할 때 스크린 리더가 읽습니다. 버튼이 아이콘만 포함하거나, 기존 텍스트 외의 다른 설명이 필요하면 버튼의 htmlAttributes 속성에 aria-label을 전달해 버튼에 라벨을 할당해야 합니다.

Angular

const toast = await this.toastController.create({
  header: 'Header',
  buttons: [
    {
      icon: 'close',
      htmlAttributes: {
        'aria-label': 'close',
      },
    },
  ],
});

Javascript

const toast = await this.toastController.create({
  header: 'Header',
  buttons: [
    {
      icon: 'close',
      htmlAttributes: {
        'aria-label': 'close',
      },
    },
  ],
});

React

useIonToast({
  header: 'Header',
  buttons: [
    {
      icon: 'close',
      htmlAttributes: {
        'aria-label': 'close',
      },
    },
  ],
});

Vue

const toast = await toastController.create({
  header: 'Header',
  buttons: [
    {
      icon: 'close',
      htmlAttributes: {
        'aria-label': 'close',
      },
    },
  ],
});

팁

완전한 목록은 아니지만, 토스트를 사용할 때 따라야 할 몇 가지 지침이 있습니다.

  • 토스트를 닫는 데 사용자 상호작용을 요구하지 마세요. 예를 들어 토스트에 "Dismiss" 버튼이 있는 것은 괜찮지만, 토스트는 타임아웃 기간 후에 자동으로 닫혀야 합니다. 알림에 사용자 상호작용이 필요하다면 alert 사용을 고려하세요.
  • 메시지가 긴 토스트의 경우 duration 속성을 조정해 사용자가 토스트의 내용을 읽을 충분한 시간을 주는 것을 고려하세요.
  • 토스트에 버튼을 추가한다면, 각 버튼과 관련된 작업을 완료하는 대체 방법을 항상 제공하세요. 이는 사용자가 토스트를 읽기 전에 닫히더라도 토스트에 표시된 작업을 완료할 수 있도록 보장합니다.
  • modal 같은 다른 오버레이 안에서 버튼이 있는 토스트를 표시하는 것은 피하세요. Modal과 다른 오버레이는 포커스 트래핑을 구현해 스크린 리더가 토스트로 포커스를 이동해 작업을 완료하는 것을 막습니다. 토스트는 여전히 스크린 리더가 안내하므로 사용자에게 혼란스러울 수 있습니다. 이는 각 버튼과 관련된 작업을 완료하는 대체 방법이 구현되어 있어도 마찬가지입니다. 토스트를 사용하는 대신 포커스가 트래핑된 modal 안에 라이브 영역을 만드는 것을 고려하세요.

인터페이스

ToastButton

interface ToastButton {
  text?: string;
  icon?: string;
  side?: 'start' | 'end';
  role?: 'cancel' | string;
  htmlAttributes?: { [key: string]: any };
  handler?: () => boolean | void | Promise<boolean | void>;
}

ToastOptions

interface ToastOptions {
  header?: string;
  message?: string | IonicSafeString;
  cssClass?: string | string[];
  duration?: number;
  buttons?: (ToastButton | string)[];
  position?: 'top' | 'bottom' | 'middle';
  translucent?: boolean;
  animated?: boolean;
  icon?: string;
  htmlAttributes?: { [key: string]: any };

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

  enterAnimation?: AnimationBuilder;
  leaveAnimation?: AnimationBuilder;
}

속성 (Properties)

animated

설명: true이면 토스트가 애니메이션됩니다.

속성: animated

타입: boolean

기본값: true

buttons

설명: 토스트의 버튼 배열입니다.

속성: undefined

타입: (string | ToastButton)[] | undefined

기본값: undefined

color

설명: 애플리케이션의 색상 팔레트에서 사용할 색상입니다. 기본 옵션은 "primary", "secondary", "tertiary", "success", "warning", "danger", "light", "medium", "dark"입니다. 색상에 대한 자세한 내용은 테마를 참조하세요.

속성: color

타입: "danger" | "dark" | "light" | "medium" | "primary" | "secondary" | "success" | "tertiary" | "warning" | string | undefined

기본값: undefined

cssClass

설명: 커스텀 CSS를 적용하기 위한 추가 클래스입니다. 여러 클래스가 제공되면 공백으로 구분해야 합니다.

속성: css-class

타입: string | string[] | undefined

기본값: undefined

duration

설명: 토스트를 숨기기 전에 기다릴 밀리초 수입니다. 기본적으로 dismiss()가 호출될 때까지 표시됩니다.

속성: duration

타입: number

기본값: config.getNumber('toastDuration', 0)

enterAnimation

설명: 토스트가 표시될 때 사용할 애니메이션입니다.

속성: undefined

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

기본값: undefined

설명: 토스트에 표시될 헤더입니다.

속성: header

타입: string | undefined

기본값: undefined

htmlAttributes

설명: 토스트에 전달할 추가 속성입니다.

속성: undefined

타입: undefined | { [key: string]: any; }

기본값: undefined

icon

설명: 표시할 아이콘의 이름 또는 유효한 SVG 파일 경로입니다. ion-icon을 참조하세요. https://ionic.io/ionicons

속성: icon

타입: string | undefined

기본값: undefined

isOpen

설명: true이면 토스트가 열립니다. false이면 토스트가 닫힙니다. 표시를 더 세밀하게 제어해야 한다면 이 옵션을 사용하고, 그렇지 않으면 toastController 또는 trigger 속성을 사용하세요. 참고: isOpen은 토스트가 닫힐 때 자동으로 false로 설정되지 않습니다. 코드에서 직접 그렇게 해야 합니다.

속성: is-open

타입: boolean

기본값: false

keyboardClose

설명: true이면 오버레이가 표시될 때 키보드가 자동으로 닫힙니다.

속성: keyboard-close

타입: boolean

기본값: false

layout

설명: 토스트 안에서 메시지와 버튼이 어떻게 배치되는지 정의합니다. 'baseline': 메시지와 버튼이 같은 줄에 나타납니다. 메시지 텍스트는 메시지 컨테이너 안에서 줄바꿈될 수 있습니다. 'stacked': 버튼 컨테이너와 메시지가 서로 위에 쌓입니다. 버튼에 긴 텍스트가 있다면 이것을 사용하세요.

속성: layout

타입: "baseline" | "stacked"

기본값: 'baseline'

leaveAnimation

설명: 토스트가 닫힐 때 사용할 애니메이션입니다.

속성: undefined

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

기본값: undefined

message

설명: 토스트에 표시될 메시지입니다. 이 속성은 문자열로 커스텀 HTML을 허용합니다. 콘텐츠는 기본적으로 일반 텍스트로 구문 분석됩니다. 커스텀 HTML을 사용하려면 Ionic 구성에서 innerHTMLTemplatesEnabled를 true로 설정해야 합니다.

속성: message

타입: IonicSafeString | string | undefined

기본값: undefined

mode

설명: mode는 사용할 플랫폼 스타일을 결정합니다. 이것은 초기화 중에 한 번 설정되고 초기 렌더 후 값을 변경해도 업데이트되지 않는 가상 속성입니다.

속성: mode

타입: "ios" | "md"

기본값: undefined

position

설명: 화면에서 토스트의 시작 위치입니다. positionAnchor 속성으로 더 조정할 수 있습니다.

속성: position

타입: "bottom" | "middle" | "top"

기본값: 'bottom'

positionAnchor

설명: 토스트의 위치를 고정할 요소입니다. 직접 참조 또는 요소의 ID로 설정할 수 있습니다. position="bottom"을 사용하면 토스트는 선택한 요소 위에 놓입니다. position="top"을 사용하면 토스트는 선택한 요소 아래에 놓입니다. position="middle"을 사용하면 positionAnchor의 값은 무시됩니다.

속성: position-anchor

타입: HTMLElement | string | undefined

기본값: undefined

swipeGesture

설명: 'vertical'로 설정하면 Toast를 스와이프 제스처로 닫을 수 있습니다. 스와이프 방향은 position 속성의 값에 따라 결정됩니다: top: Toast를 위로 스와이프해 닫을 수 있습니다. bottom: Toast를 아래로 스와이프해 닫을 수 있습니다. middle: Toast를 위나 아래로 스와이프해 닫을 수 있습니다.

속성: swipe-gesture

타입: "vertical" | undefined

기본값: undefined

translucent

설명: true이면 토스트가 반투명하게 됩니다. mode가 "ios"이고 기기가 backdrop-filter를 지원할 때만 적용됩니다.

속성: translucent

타입: boolean

기본값: false

trigger

설명: 클릭 시 토스트를 열게 하는 트리거 요소에 해당하는 ID입니다.

속성: trigger

타입: string | undefined

기본값: undefined

이벤트

Name Description Bubbles
didDismiss 토스트가 닫힌 후 발생합니다. ionToastDidDismiss의 단축형입니다. true
didPresent 토스트가 표시된 후 발생합니다. ionToastWillDismiss의 단축형입니다. true
ionToastDidDismiss 토스트가 닫힌 후 발생합니다. true
ionToastDidPresent 토스트가 표시된 후 발생합니다. true
ionToastWillDismiss 토스트가 닫히기 전에 발생합니다. true
ionToastWillPresent 토스트가 표시되기 전에 발생합니다. true
willDismiss 토스트가 닫히기 전에 발생합니다. ionToastWillDismiss의 단축형입니다. true
willPresent 토스트가 표시되기 전에 발생합니다. ionToastWillPresent의 단축형입니다. true

메서드

dismiss

설명: 표시된 후 토스트 오버레이를 닫습니다. 오버레이가 아직 표시되지 않았다면 아무 작업도 하지 않습니다. 표시된 적이 없는 오버레이를 DOM에서 제거하려면 remove 메서드를 사용하세요.

시그니처: dismiss(data?: any, role?: string) => Promise<boolean>

매개변수: data: 닫힘 이벤트에서 발생시킬 모든 데이터. role: 토스트를 닫는 요소의 역할. 버튼 핸들러에서 어떤 버튼이 클릭되어 토스트를 닫았는지 결정하는 데 유용할 수 있습니다. 몇 가지 예는 "cancel", "destructive", "selected", "backdrop"입니다.

onDidDismiss

설명: 토스트가 닫힐 때 해결되는 promise를 반환합니다.

시그니처: onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>

onWillDismiss

설명: 토스트가 닫히려 할 때 해결되는 promise를 반환합니다.

시그니처: onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>

present

설명: 생성된 후 토스트 오버레이를 표시합니다.

시그니처: present() => Promise<void>

CSS Shadow Parts

Name Description
button 토스트 안에 표시되는 모든 버튼 요소.
button cancel 역할이 "cancel"인 토스트 안에 표시되는 모든 버튼 요소.
container 아이콘, 콘텐츠, 버튼을 그룹화합니다.
content 헤더와 메시지를 포함하는 라이브 영역.
header 토스트의 헤더 텍스트.
icon 토스트 콘텐츠 옆에 나타나는 아이콘.
message 토스트의 본문 텍스트.
wrapper 토스트 오버레이의 바깥 래퍼.

CSS 사용자 정의 속성

iOS

Name Description
--background 토스트의 배경
--border-color 토스트의 테두리 색상
--border-radius 토스트의 테두리 반경
--border-style 토스트의 테두리 스타일
--border-width 토스트의 테두리 너비
--box-shadow 토스트의 박스 그림자
--button-color 버튼 텍스트의 색상
--color 토스트 텍스트의 색상
--end 방향이 왼쪽에서 오른쪽이면 오른쪽에서, 오른쪽에서 왼쪽이면 왼쪽에서 위치
--height 토스트의 높이
--max-height 토스트의 최대 높이
--max-width 토스트의 최대 너비
--min-height 토스트의 최소 높이
--min-width 토스트의 최소 너비
--start 방향이 왼쪽에서 오른쪽이면 왼쪽에서, 오른쪽에서 왼쪽이면 오른쪽에서 위치
--white-space 토스트 메시지의 공백
--width 토스트의 너비

MD

Name Description
--background 토스트의 배경
--border-color 토스트의 테두리 색상
--border-radius 토스트의 테두리 반경
--border-style 토스트의 테두리 스타일
--border-width 토스트의 테두리 너비
--box-shadow 토스트의 박스 그림자
--button-color 버튼 텍스트의 색상
--color 토스트 텍스트의 색상
--end 방향이 왼쪽에서 오른쪽이면 오른쪽에서, 오른쪽에서 왼쪽이면 왼쪽에서 위치
--height 토스트의 높이
--max-height 토스트의 최대 높이
--max-width 토스트의 최대 너비
--min-height 토스트의 최소 높이
--min-width 토스트의 최소 너비
--start 방향이 왼쪽에서 오른쪽이면 왼쪽에서, 오른쪽에서 왼쪽이면 오른쪽에서 위치
--white-space 토스트 메시지의 공백
--width 토스트의 너비

슬롯

이 컴포넌트에 사용 가능한 슬롯이 없습니다.

더 알아보기 (Learn more)

ion-toast은 사용자에게 조용히 상태를 알려주는 오버레이예요. trigger나 isOpen으로 표시를 제어하고, position/positionAnchor로 위치를, layout으로 버튼 배치를 정할 수 있어요. 사용자를 방해하지 않도록 aria-live="polite"를 유지하고, 중요한 메시지는 alert를 쓰는 게 좋아요.