Descripción general de los componentes de Angular Toast

    El componente Ignite UI for Angular Toast proporciona información y mensajes de advertencia que se ocultan automáticamente, no interactúan y no pueden ser descartados por el usuario. Las notificaciones se pueden mostrar en la parte inferior, central o superior de la página.

    Angular Toast Example

    Getting Started with Ignite UI for Angular Toast

    Para comenzar con el componente Ignite UI for Angular Toast, 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 importarlosIgxToastModule en tu archivo app.module.ts.

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

    Alternativamente,16.0.0 puedes importarlosIgxToastComponent como una dependencia independiente.

    // home.component.ts
    
    import { IgxToastComponent } from 'igniteui-angular/toast';
    import { IgxButtonDirective } from 'igniteui-angular/directives';
    // import { IgxToastComponent, IgxButtonDirective } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <button igxButton="contained" (click)="toast.open()">Show notification</button>
        <igx-toast #toast>Notification displayed</igx-toast>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IgxToastComponent, IgxButtonDirective]
        /* or imports: [IgxTimePickerComponent, IgxButtonDirective] */
    })
    export class HomeComponent {
        public time: Date;
    }
    

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

    Using the Angular Toast

    Show Toast

    In order to display the toast component, use its open() method and call it on a button click. You can pass the toast content inside the element.

    <!--sample.component.html-->
    
    <button igxButton="contained" (click)="toast.open()">Show notification</button>
    <igx-toast #toast>Notification displayed</igx-toast>
    

    Another way to set the toast content is to directly pass the message as a parameter to the open() method.

    <!--sample.component.html-->
    
    <button igxButton="contained" (click)="toast.open('Notification displayed')">Show notification</button>
    <igx-toast #toast></igx-toast>
    

    The open() method can also be used in the AppComponent file to manage the value of the message.

    // app.component.ts
    @ViewChild('toast', { read: IgxToastComponent }) public toast: IgxToastComponent;
    
    public message: any;
    
    public ngOnInit() {
        this.message = 'Display message';
    }
    
    public showMessage() {
        this.toast.open(this.message);
    }
    

    Examples

    Hide/Auto Hide

    Once opened, the toast 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 this by setting autoHide to false. This way, the toast remains visible. Using the toast close() method, you can close the component.

    <!--sample.component.html-->
    
    <button igxButton="contained" (click)="toast.open()">Show Toast</button>
    <button igxButton="contained" (click)="toast.close()">Hide Toast</button>
    <igx-toast #toast [autoHide]="false">Notification displayed</igx-toast>
    

    If the sample is configured properly, the toast will appear when the Show button is clicked. For the first component auto-hide feature is disabled and the toast will disappear on 'Hide' button click. In the other two components you can see in action how to pass different messages through the open() method and use content projection.

    Display Time

    Use displayTime and set it to an interval in milliseconds to configure how long the toast component is visible.

    <!--sample.component.html-->
    
    <button igxButton="contained" (click)="toast.open()">Show notification</button>
    <igx-toast #toast displayTime="1000">Notification displayed</igx-toast>
    

    Si la muestra está configurada correctamente, el sistema se oculta automáticamente más rápido.

    Positioning

    Use positionSettings property to configure where the toast 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-->
    <div>
        <button igxButton="contained" (click)="open(toast)">Show notification on top</button>
        <igx-toast #toast>Notification displayed</igx-toast>
    </div>
    
    // sample.component.ts
    import { VerticalAlignment } from 'igniteui-angular/core';
    // import { VerticalAlignment } from '@infragistics/igniteui-angular'; for licensed package
    ...
    public open(toast) {
        toast.positionSettings.verticalDirection = VerticalAlignment.Top;
        toast.open();
    }
    ...
    

    Estilismo

    Toast 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 para el brindis.
    $text-color $border color El color del borde usado para la tostada.

    Para comenzar a diseñar el brindis, 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 toast-theme and provide the $background, $text-color and $border-radius parameters.

    $custom-toast-theme: toast-theme(
      $text-color: #ffcd0f,
      $background: #292826,
      $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 pasar el tema de brindis personalizado:

    @include css-vars($custom-toast-theme);
    

    Demo

    Styling with Tailwind

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

    Junto con la importación de Tailwind en tu hoja de estilos global, puedes 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-toast,dark-toast.

    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 IgxToast. La sintaxis es la siguiente:

    <igx-toast
      class="!light-toast ![--background:#90B69F]">
      ...
    </igx-toast>
    
    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 tostada debería verse así:

    API References

    Additional Resources

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