Angular 스낵바 구성 요소 개요

    Ignite UI for Angular 작업을 포함할 수 있는 한 줄 메시지로 작업에 대한 피드백을 제공합니다. 스낵바 메시지는 다른 모든 요소 위에 나타나며 화면 하단 중앙에 위치합니다.

    Angular Snackbar Example

    Getting Started with Ignite UI for Angular Snackbar

    Ignite UI for Angular Snackbar 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.

    ng add igniteui-angular
    

    Ignite UI for Angular에 대한 전체 소개를 보려면 시작하기 항목을 읽어보세요.

    다음 단계는 IgxSnackbarModule 당신의 app.module.ts 파일.

    // app.module.ts
    
    ...
    import { IgxSnackbarModule } from 'igniteui-angular';
    // import { IgxSnackbarModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxSnackbarModule],
        ...
    })
    export class AppModule {}
    

    또는 16.0.0부터 IgxSnackbarComponent 독립형 종속성으로 가져올 수 있습니다.

    // home.component.ts
    
    import { IgxSnackbarComponent, IgxButtonDirective } from 'igniteui-angular';
    // import { IgxSnackbarComponent, IgxButtonDirective } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <button igxButton="contained" (click)="snackbar.open()">Delete Message</button>
        <div>
            <igx-snackbar #snackbar>Message deleted</igx-snackbar>
        </div>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IgxSnackbarComponent, IgxButtonDirective]
    })
    export class HomeComponent {}
    

    이제 Ignite UI for Angular 가져왔으므로 igx-snackbar 구성 요소 사용을 시작할 수 있습니다.

    Using the Angular Snackbar

    Show Snackbar

    스낵바 구성 요소를 표시하려면 open() 메서드를 사용하고 버튼 클릭 시 호출합니다.

    <!--sample.component.html-->
    
    <button igxButton="contained" (click)="snackbar.open()">Delete Message</button>
    <div>
        <igx-snackbar #snackbar>Message deleted</igx-snackbar>
    </div>
    

    샘플이 올바르게 구성되면 데모 샘플이 표시됩니다. 버튼을 클릭하면 문자 메시지를 표시하는 스낵바가 나타납니다. 위의 코드 조각에서 볼 수 있듯이 스낵바에 표시되는 마사지를 설정하는 한 가지 방법은 콘텐츠 프로젝션을 사용하는 것입니다. 그러나 일부 사용자 정의 논리를 기반으로 프로그래밍 방식으로 값을 전환해야 하는 경우 해당 값을 open() 메서드에 매개 변수로 전달하면 됩니다.

    <!--sample.component.html-->
    
    <button igxButton="contained" (click)="snackbar.open('Message deleted')">Delete Message</button>
    <button igxButton="contained" (click)="snackbar.open('Message deletion was not successful. Please try again')">Delete Message</button>
    <div>
        <igx-snackbar #snackbar></igx-snackbar>
    </div>
    

    Hide/Auto Hide

    스낵바는 일단 열리면 처음에 4000밀리초로 설정된 displayTime 입력에 지정된 기간이 지나면 사라집니다. 이 동작은 기본적으로 활성화되어 있지만 autoHide​ ​false로 설정하여 변경할 수 있습니다. 이렇게 하면 스낵바가 계속 표시됩니다. 스낵바 close() 메소드를 사용하면 코드에서 구성요소를 닫을 수 있습니다.

    <!--sample.component.html-->
    
    <button igxButton="contained" (click)="snackbar.open()">Send message</button>
    <div>
      <igx-snackbar #snackbar [autoHide]="false" actionText="CLOSE" (clicked)="close(snackbar)">Message sent</igx-snackbar>
    </div>
    
    // sample.component.ts
    
    public close(element) {
        element.close();
    }
    

    샘플이 올바르게 구성된 경우 버튼을 클릭하면 첫 번째 스낵바가 나타나 메시지작업 버튼을 모두 표시합니다. 'CLOSE' 버튼을 클릭하면 자동 숨기기 기능이 비활성화되고 스낵바가 사라집니다. 또 다른 스낵바는 open() 메서드를 통해 다른 메시지를 전달하고 표시 시간이 만료되면 이를 숨깁니다. 세 번째 구성 요소는 메시지를 open() 메서드에 매개변수로 전달하고 콘텐츠 프로젝션을 사용하여 아이콘을 추가합니다.

    Display Time

    displayTime 사용하고 간격을 밀리초 단위로 설정하여 스낵바 구성 요소가 표시되는 시간을 구성합니다. 기본적으로 앞서 말했듯이 처음에는 4000밀리초로 설정되어 있습니다.

    Customize Snackbar

    메시지와 버튼보다 더 복잡한 요소를 표시하도록 스낵바의 콘텐츠를 사용자 정의할 수도 있습니다. 예를 들어, 파일을 로드하는 동안 스낵바를 표시하려는 경우 로딩 애니메이션을 해당 콘텐츠에 추가할 수 있습니다.

    <!--sample.component.html-->
    <button igxButton="contained" (click)="snackbar.open()">Load file</button>
    <div>
      <igx-snackbar #snackbar displayTime="5000">File loading
        <svg id="dots" height="20px">
            <g id="dots" fill="#FFFFFF">
                <circle id="dot1" cx="5" cy="18" r="2"></circle>
                <circle id="dot2" cx="15" cy="18" r="2"></circle>
                <circle id="dot3" cx="25" cy="18" r="2"></circle>
            </g>
        </svg>
      </igx-snackbar>
    </div>
    
    //sample.component.scss
    #dots #dot1 {
        animation: load 1s infinite;
    }
    
    #dots #dot2 {
        animation: load 1s infinite;
        animation-delay: 0.2s;
    }
    
    #dots #dot3 {
        animation: load 1s infinite;
        animation-delay: 0.4s;
    }
    
    @keyframes load {
        0% {
          opacity: 0;
        }
        50% {
          opacity: 1;
        }
        100% {
          opacity: 0;
        }
    }
    

    결과적으로 스낵바에 메시지와 3개의 로딩 점이 나타납니다.

    Snackbar in list

    모든 주요 스낵바 기능을 다루면 이 구성 요소를 보다 흥미로운 시나리오에 통합할 수 있습니다. 스낵바를 사용하여 알림을 제공하고 작업을 되돌리는 기능을 제공할 수 있습니다.

    삭제할 수 있는 연락처 목록을 만들어 보겠습니다. 항목이 삭제되면 메시지와 작업 실행 취소 버튼이 포함된 스낵바가 표시됩니다.

    <!--sample.component.html-->
    <igx-list>
        <igx-list-item [isHeader]="true">Contacts</igx-list-item>
    
        <igx-list-item igxRipple="pink" igxRippleTarget=".igx-list__item" *ngFor="let item of navItems">
            <div class="item-container">
                <div class="contact">
                    <igx-avatar [src]="item.avatar" shape="circle"></igx-avatar>
                    <div class="contact__info">
                        <span class="name">{{item.text}}</span>
                    </div>
                </div>
                <span igxIconButton="flat" igxRipple igxRippleCentered="true" (click)="delete(item)">
                    <igx-icon [style.color]="'#ff5252'">delete</igx-icon>
                </span>
            </div>
    
        </igx-list-item>
    
        <igx-snackbar actionText="Undo" (clicked)="restore()">Contact deleted</igx-snackbar>
    </igx-list>
    
    //sample.component.ts
    
    import { Component, OnInit, ViewChild } from '@angular/core';
    import { IgxSnackbarComponent } from 'igniteui-angular';
    // import { IgxSnackbarComponent } from '@infragistics/igniteui-angular'; for licensed package
    ...
    @ViewChild(IgxSnackbarComponent)
    public snackbar: IgxSnackbarComponent;
    public navItems: any[];
    public deletedItems = [];
    
    constructor() { }
    
    public ngOnInit() {
        this.navItems = [
            { avatar: 'assets/images/avatar/2.jpg', text: 'Richard Mahoney'},
            { avatar: 'assets/images/avatar/4.jpg', text: 'Lisa Landers' },
            { avatar: 'assets/images/avatar/14.jpg', text: 'Marianne Taylor' },
            { avatar: 'assets/images/avatar/17.jpg', text: 'Ward Riley' }
        ];
    }
    
    public delete(item) {
        this.deletedItems.push([item, this.navItems.indexOf(item)]);
        this.navItems.splice(this.navItems.indexOf(item), 1);
        this.snackbar.open();
    }
    
    public restore() {
        const [item, index] = this.deletedItems.pop();
        this.navItems.splice(index, 0, item);
        this.snackbar.close();
    }
    

    Overlay Settings

    IgxSnackbarComponent오버레이 설정을 사용하여 컨테이너의 위치를 제어합니다. 기본 설정은 Custom OverlaySettings를 정의하고 스낵바 open() 메서드에 전달하여 변경할 수 있습니다.

    public customSettings: OverlaySettings = {
        positionStrategy: new GlobalPositionStrategy(
            { 
                horizontalDirection: HorizontalAlignment.Left,
                verticalDirection: VerticalAlignment.Top
            }),
        modal: true,
        closeOnOutsideClick: true,
    };
    
    snackbar.open(customSettings);
    

    사용자는 스낵바가 표시될 때 DOM에 배치될 특정 콘센트를 제공할 수도 있습니다.

    <igx-snackbar [outlet]="igxBodyOverlayOutlet"></igx-snackbar>
    <div #igxBodyOverlayOutlet igxOverlayOutlet></div>
    

    스타일링

    스낵바 스타일링을 시작하려면 모든 테마 기능과 구성 요소 믹스인이 있는 인덱스 파일을 가져와야 합니다.

    @use "igniteui-angular/theming" as *;
    
    // IMPORTANT: Prior to Ignite UI for Angular version 13 use:
    // @import '~igniteui-angular/lib/core/styles/themes/index';
    

    가장 간단한 접근 방식에 따라 snackbar-theme 확장하고 $text-color, $background, $button-color$border-radius 매개변수를 허용하는 새 테마를 만듭니다.

    $dark-snackbar: snackbar-theme(
        $text-color: #FFCD0F,
        $background: #292826,
        $button-color: #FFCD0F,
        $border-radius: 12px
    );
    

    Including themes

    마지막 단계는 애플리케이션에 구성 요소 테마를 포함하는 것입니다.

    $legacy-support​ ​true로 설정된 경우 다음과 같은 구성 요소 테마를 포함합니다.

     @include snackbar($igx-snackbar-theme);
    
    Note

    구성 요소가 Emulated ViewEncapsulation을 사용하는 경우::ng-deep 사용하여 이 캡슐화를 penetrate 해야 합니다.

    :host {
         ::ng-deep {
            @include snackbar($igx-snackbar-theme);
        }
    }
    

    $legacy-support​ ​false (기본값)로 설정된 경우 다음과 같은 구성 요소 CSS 변수를 포함합니다.

    @include css-vars($igx-snackbar-theme);
    
    Note

    구성 요소가 Emulated ViewEncapsulation을 사용하는 경우 변수를 재정의하려면 전역 선택기가 필요하므로 여전히:host 사용해야 합니다.

    :host {
        @include css-vars($igx-snackbar-theme);
    }
    

    Defining a color palette

    방금 했던 것처럼 색상 값을 하드코딩하는 대신 igx-paletteigx-color 기능을 사용하면 색상 측면에서 더 큰 유연성을 얻을 수 있습니다.

    igx-palette 전달된 기본 색상과 보조 색상을 기반으로 색상 팔레트를 생성합니다.

    $yellow-color: #FFCD0F;
    $black-color: #292826;
    
    $dark-palette: palette($primary: $black-color, $secondary: $yellow-color);
    

    그런 다음 igx-color 사용하면 팔레트에서 색상을 쉽게 검색할 수 있습니다.

    $dark-snackbar: snackbar-theme(
        $text-color: color($dark-palette, "secondary", 400),
        $background: color($dark-palette, "primary", 400),
        $button-color: color($dark-palette, "secondary", 400),
        $border-radius: 12px
    );
    
    Note

    igx-colorigx-palette 색상을 생성하고 검색하는 강력한 기능입니다. 사용 방법에 대한 자세한 지침은 Palettes 항목을 참조하세요.

    Using Schemas

    테마 엔진을 사용하면 스키마의 이점을 활용하는 강력하고 유연한 구조를 구축할 수 있습니다. 스키마는 테마의 레시피입니다.

    모든 구성 요소에 대해 제공되는 사전 정의된 두 스키마 중 하나(이 경우 dark-snackbar 스키마)를 확장합니다.

    //  Extending the dark snackbar schema
    $dark-snackbar-schema: extend($_dark-snackbar,
        (
            text-color:(
               color: ("secondary", 400)
            ),
            background: (
               color: ("primary", 400)
            ),
            button-color: (
               color: ("secondary", 400)
            ),
            border-radius: 12px
        )
    );
    

    사용자 정의 스키마를 적용하려면 다음을 수행해야 합니다. 연장하다 전역 변수 중 하나(light 또는 dark)는 기본적으로 사용자 정의 스키마를 사용하여 구성 요소를 지적한 후 해당 구성 요소 테마에 추가합니다.

    // Extending the global dark-schema
    $custom-dark-schema: extend($dark-schema,(
        igx-snackbar: $dark-snackbar-schema
    ));
    
    // Defining snackbar theme with the global dark schema
    $dark-snackbar: snackbar-theme(
      $palette: $dark-palette,
      $schema: $custom-dark-schema
    );
    

    위에서 설명한 것과 동일한 방식으로 테마를 포함하는 것을 잊지 마십시오.

    Demo

    API References

    이 기사에서는 IgxSnackbarComponent 사용하고 구성하는 방법을 배웠습니다. API에 대한 자세한 내용은 아래 링크를 참조하세요.

    Styles:

    Additional Resources

    Our community is active and always welcoming to new ideas. * [Ignite UI for Angular **Forums**](https://ko.infragistics.com/community/forums/f/ignite-ui-for-angular) * [Ignite UI for Angular **GitHub**](https://github.com/IgniteUI/igniteui-angular)