Descripción general del componente Snackbar Angular

    El componente Ignite UI for Angular Snackbar proporciona información sobre una operación con un mensaje de una sola línea, que puede incluir una acción. El mensaje de Snackbar aparece por encima de todos los demás elementos y se coloca en la parte inferior central de la pantalla.

    Angular Snackbar Example

    Getting Started with Ignite UI for Angular Snackbar

    Para comenzar con el componente Ignite UI for Angular Snackbar, primero debe instalar Ignite UI for Angular. En una aplicación Angular existente, escriba el siguiente comando:

    ng add igniteui-angular
    

    Para obtener una introducción completa al Ignite UI for Angular, lea el tema de introducción.

    El siguiente paso es importarlosIgxSnackbarModule en tu archivo app.module.ts.

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

    Alternativamente,16.0.0 puedes importarlosIgxSnackbarComponent como una dependencia independiente.

    // home.component.ts
    
    import { IgxSnackbarComponent } from 'igniteui-angular/snackbar';
    import { IgxButtonDirective } from 'igniteui-angular/directives';
    // 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 {}
    

    Now that you have the Ignite UI for Angular Snackbar module or component imported, you can start using the igx-snackbar component.

    Using the Angular Snackbar

    Show Snackbar

    In order to display the snackbar component, use its open() method and call it on a button click.

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

    If the sample is configured properly, you should see the demo sample. A snackbar appears displaying a text message when the button is clicked. As you can see in the code snippet above, one way to set the massage displayed in the snackbar is to use the content projection. But if you need to switch the value programmatically based on some custom logic you can just pass the value as a parameter to the open() method.

    <!--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

    Once opened, the snackbar disappears after a period specified by the displayTime input which is set initially to 4000 milliseconds. This behavior is enabled by default but you can change it by setting autoHide to false. In this way, the snackbar will remain visible. Using the snackbar close() method, you can close the component in the code.

    <!--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();
    }
    

    If the sample is configured properly, the first snackbar appears when the button is clicked, showing both the message and action button. The auto-hide feature is disabled and the snackbar disappears on 'CLOSE' button click. Another snackbar passes a different message through the open() method and hides it when the display time expires. The third component passes a message as a param to the open() method and adds an icon using content projection.

    Display Time

    Use displayTime and set it to an interval in milliseconds to configure how long the snackbar component is visible. By default, as we said, it's initially set to 4000 milliseconds.

    Customize Snackbar

    También podemos personalizar el contenido del Snackbar para mostrar elementos más complejos que un mensaje y un botón. Si queremos mostrar la snackbar mientras cargamos un archivo, por ejemplo, se podría añadir una animación de carga a su contenido.

    <!--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;
        }
    }
    

    Como resultado, aparecen un mensaje y tres puntos de carga en la barra de snacks.

    Snackbar in list

    Habiendo cubierto todas las características principales del snackbar, podemos integrar este componente en un escenario más interesante. Podemos utilizar el snackbar para proporcionar una notificación y la posibilidad de revertir acciones.

    Creemos una lista con contactos que se pueden eliminar. Cuando se elimina un elemento, se muestra una barra de bocadillos que contiene un mensaje y un botón para deshacer la acción.

    <!--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/snackbar';
    // 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();
    }
    

    Positioning

    Use positionSettings property to configure where the snackbar appears. By default, it is displayed at the bottom of the page. In the sample below, we set notification to appear at the top position.

    <!--sample.component.html-->
    <button igxButton="contained" (click)="open(snackbar)">Show notification on top</button>
    <igx-snackbar #snackbar>Notification displayed</igx-snackbar>
    
    // sample.component.ts
    import { VerticalAlignment, HorizontalAlignment } from 'igniteui-angular/core';
    // import { VerticalAlignment, HorizontalAlignment } from '@infragistics/igniteui-angular'; for licensed package
    ...
    public open(snackbar) {
        snackbar.positionSettings.verticalDirection = VerticalAlignment.Top;
        snackbar.positionSettings.horizontalDirection = HorizontalAlignment.Right;
        snackbar.open();
    }
    ...
    

    Estilismo

    Snackbar Theme Property Map

    Al modificar una propiedad principal, todas las propiedades dependientes relacionadas se actualizan automáticamente para reflejar el cambio:

    Propiedad principal Propiedad dependiente Descripción
    $background $text-color El color del texto usado en la barra de aperitivos
    $button colorEl color de botón usado en la barra de aperitivos

    Para comenzar a diseñar el snackbar, necesitamos importar el archivo de índice, donde se encuentran todas las funciones del tema y los mixins de componentes:

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

    Following the simplest approach, we create a new theme that extends the snackbar-theme and accepts the $text-color, $background, $button-color and the $border-radius parameters.

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

    En lugar de codificar los valores de color como acabamos de hacer, podemos lograr mayor flexibilidad en cuanto a colores usando laspalette funciones ycolor. Por favor, consulta elPalettes tema para obtener una guía detallada sobre cómo utilizarlos.

    El último paso es incluir el tema del componente en nuestra aplicación.

    @include css-vars($dark-snackbar);
    

    Demo

    Styling with Tailwind

    Puedes decorar el snackbar usando nuestras clases utilitarias personalizadas de Tailwind. Asegúrate de configurar primero a Tailwind.

    Junto con la importación de viento de cola en su hoja de estilo global, puede aplicar las utilidades de tema deseadas de la siguiente manera:

    @import "tailwindcss";
    ...
    @use 'igniteui-theming/tailwind/utilities/material.css';
    

    El archivo de utilidad incluye variantes tantolight comodark de tema.

    • Usalight-* clases para el tema ligero.
    • Usadark-* clases para el tema oscuro.
    • Añadir el nombre del componente después del prefijo, por ejemplo, ,light-snackbar,dark-snackbar.

    Una vez aplicadas, estas clases permiten cálculos dinámicos de temas. Desde ahí, puedes anular las variables CSS generadas usandoarbitrary properties. Después de los dos puntos, proporciona cualquier formato de color CSS válido (HEX, variable CSS, RGB, etc.).

    Puedes encontrar la lista completa de propiedades en el tema de la barra de aperitivos. La sintaxis es la siguiente:

    <igx-snackbar
      class="!light-snackbar ![--background:#7B9E89]
      ![--button-color:#DD0D4B]">
      ...
    </igx-snackbar>
    
    Note

    El signo de exclamación(!) es necesario para asegurar que la clase de utilidad tenga prioridad. Tailwind aplica estilos en capas y, sin marcar estos estilos como importantes, serán anulados por el tema predeterminado del componente.

    Al final, tu barra de snacks debería verse así:

    API References

    In this article we learned how to use and configure the IgxSnackbarComponent. For more details in regards its API, take a look at the links below:

    Styles:

    Additional Resources

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.