본문 바로가기
✔️ Development

[Salesforce] LWC Popup Notifications 들에 대해 알아보자! (Alert, Confirm, Prompt)

by 보리눙나 2024. 3. 25.

안녕하셀포~🌺💥

 


toastMessage 및 Window.alert(), Window.confirm(), Window.prompt()

 

여러분은 위 사진과 같이 시스템 작업이나 이벤트에 대해 짧게 메세지로 띄워주는 toast notification을 주로 쓰시거나, Javascript에서 기본적으로 제공하는 window.alert(), window.confirm(), window.prompt() 메소드를 이용하시나요 ?

 

이번엔 보다 더 많은 기능과 UI를 제공하는 LWC Popup Notifications(총 3가지) 에 대해 알아보겠습니다.😎

Notification Popup은 사용자가 확인 또는 취소를 클릭하여 메세지를 보다 정확히 확인하도록 할때 유용하게 쓸 수 있습니다.


[Attributes]

  • label : Modal의 Header Text 값
  • message : Modal Body에 보여줄 메세지
  • defaultValue : 입력 초기값. LightningPrompt에만 사용가능!
  • variant : 사용가능 한 값은 2개(header, headerless). Default 값은 header

header(왼쪽) , headerless(오른쪽)

  • theme : Header의 테마 색상을 지정
    • default: white
    • shade: gray
    • inverse: dark blue
    • alt-inverse: darker blue
    • success: green
    • info: gray-ish blue
    • warning: yellow
    • error: red
    • offline: black

theme


1. Alert 

주로 경고 메세지를 전달하는데 사용됩니다. (OK 버튼만 제공)

 

2. Confirm 

사용자에게 작업을 계속할지 아니면 취소할지 확인을 요청하는데 사용합니다. (Ok, Cancel 버튼 제공)

 

 

3. Prompt  

사용자에게 필요한 정보를 입력받을때 사용합니다. (확인 및 취소가 포함된 텍스트 입력이 있음)

대신 단일 값만 입력 받을 수 있습니다! 여러 값을 입력 받고 싶을 경우 lightning-modal 을 사용하셔야 됩니다.


 Resources 

popupNotification.html

<template>
    <lightning-card title="popup Notification Test">
        <lightning-button slot="actions" label="alert" onclick={alertPopup}></lightning-button>
        <lightning-button slot="actions" label="confirm" onclick={confirmPopup}></lightning-button>
        <lightning-button slot="actions" label="Notification" onclick={promptPopup}></lightning-button>
    </lightning-card>
</template>

 

popupNotification.js

import { LightningElement } from 'lwc';
import LightningAlert from "lightning/alert";
import LightningConfirm from 'lightning/confirm';
import LightningPrompt from 'lightning/prompt';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class PopupNotification extends LightningElement {

    async alertPopup() {
        await LightningAlert.open({
              message: "Hello!",
              theme: "success",
              label: "alert",
              variant : "headerless"
        });
    }

    async confirmPopup() {
        const result = await LightningConfirm.open({
              message: "진짜 삭제하시겠습니까?",
              theme: "error",
              label: "confirm",
        });

        if(result){
            //삭제 작업 진행
        }
    }

    async promptPopup() {
        const result = await LightningPrompt.open({
              message: "이메일을 입력해 주세요.",
              theme: "inverse",
              label: "prompt",
        });

        if(result != null && result != ''){
            if (!(/(.+)@(.+){2,}\.(.+){2,}/.test(result))) {
                this.dispatchEvent(new ShowToastEvent({
               variant: "error",
               message: "이메일 형식이 아닙니다.",
            }));
            this.promptPopup();
            }else{
                this.dispatchEvent(new ShowToastEvent({
                    variant: "success",
                    message: "완료되었습니다.",
                }));
            }
        } else if (result === null) {
            this.dispatchEvent(new ShowToastEvent({
                variant: "warning",
                message: "입력이 취소되었습니다.",
            }));
        } else {
            this.dispatchEvent(new ShowToastEvent({
                variant: "error",
                message: "이메일을 입력해주세요.",
            }));
            this.promptPopup();
        }
    }

}

 

🌟 .open() 메소드는 Promise를 반환하므로, 해당 Promise를 처리하기 위해  async/await 또는 then() 을 사용할 수 있습니다.

 

 

[Reference links]

https://developer.salesforce.com/docs/component-library/bundle/lightning-alert/documentation

 

lightning-alert - documentation - Salesforce Lightning Component Library

The lightning/alert module lets you create an alert modal within your component. Use LightningAlert on your components to communicate a state that affects the entire system, not just a feature or page. Use LightningAlert.open() instead of the native window

developer.salesforce.com

https://developer.salesforce.com/docs/component-library/bundle/lightning-confirm

 

lightning-confirm - documentation - Salesforce Lightning Component Library

The lightning/confirm module lets you create a confirm modal within your component. Use LightningConfirm on your component to ask the user to respond before they continue. Use LightningConfirm.open() instead of the native window.confirm() for a more consis

developer.salesforce.com

https://developer.salesforce.com/docs/component-library/bundle/lightning-prompt/documentation

 

lightning-prompt - documentation - Salesforce Lightning Component Library

The lightning/prompt module lets you create a prompt modal within your component. Use LightningPrompt on your components to ask the user to provide information before they continue. Use LightningPrompt.open() instead of the native window.prompt() for a mor

developer.salesforce.com