Descripción general del componente Angular Badge

    Angular Badge es un componente que se utiliza junto con avatares, menús de navegación u otros componentes de una aplicación cuando se necesita una notificación visual. Las insignias suelen estar diseñadas como íconos con un estilo predefinido para comunicar información, éxito, advertencias o errores.

    Angular Badge Example

    Getting Started with Ignite UI for Angular Badge

    Para empezar a utilizar el componente Ignite UI for Angular Badge, 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.

    The next step is to import the IgxBadgeModule in your app.module.ts file.

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

    Alternatively, as of 16.0.0 you can import the IgxBadgeComponent as a standalone dependency.

    // home.component.ts
    
    ...
    import { IgxBadgeComponent } from 'igniteui-angular/badge';
    // import { IgxBadgeComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: '<igx-badge icon="check" type="success" shape="square"></igx-badge>',
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IgxBadgeComponent]
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Badge module or component imported, you can start with a basic configuration of the igx-badge component.

    Using the Angular Badge Component

    Let's see how the demo sample is done. It's a simple success badge on an avatar. To build that, we need to import the IgxAvatarModule, along with the IgxBadgeModule:

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

    Alternatively, as of 16.0.0 you can import the IgxBadgeComponent and IgxAvatarComponent as standalone dependencies.

    A continuación, agregaremos esos componentes a nuestra plantilla:

    <div class="wrapper">
        <igx-avatar icon="person" shape="circle" size="small"></igx-avatar>
        <igx-badge icon="check" type="success"></igx-badge>
    </div>
    

    Usando el wrapper posicionaremos la insignia de manera absoluta, cubriendo un poco el avatar:

    .wrapper {
      position: relative;
      margin-top: 15px;
    }
    
    igx-badge {
      position: absolute;
      bottom: 0;
      left: 28px;
    }
    

    Badge Shape

    We can change the badge shape through the shape attribute setting its value to square. By default, the shape of the badge is rounded.

    <igx-badge icon="check" type="success" shape="square"></igx-badge>
    

    Si todo se hace correctamente, debería ver la muestra de demostración que se muestra arriba en su navegador.

    Badge Size

    The size of the badge can be controlled using the --size variable. It will make sure that the badge sizes proportionally in both directions. Keep in mind, however, that badges containing text values use the caption typography style for its font-size and line-height. For that reason, when setting the --size of a badge containing text to values below 16px, you will also need to modify its typography.

    Ejemplo:

    igx-badge {
      --size: 12px;
    
      font-size: calc(var(--size) / 2);
      line-height: normal;
    }
    

    Badge Icon

    In addition to material icons, the igx-badge component also supports usage of Material Icons Extended and any other custom icon set. To add an icon from the material icons extended set inside your badge component, first you have to register it:

    export class BadgeIconComponent implements OnInit { 
        constructor (protected _iconService: IgxIconService) {}
    
        public ngOnInit() {
            this._iconService.addSvgIconFromText(heartMonitor.name, heartMonitor.value, 'imx-icons');
        }
    }
    

    Luego, simplemente especifique el nombre del ícono y la familia de la siguiente manera:

    <igx-badge icon="heart-monitor" iconSet="imx-icons"></igx-badge>
    

    Badge in List

    Let's extend the previous sample and create a list with contacts, similar to those in chat clients. In addition to the contact name, we want to display an avatar and the current state of the contact (online, offline or away). To achieve this, we're using the igx-badge and igx-avatar components. For a container, igx-list is used.

    Para continuar, incluya todos los módulos necesarios e impórtelos en el archivo app.module.ts.

    // app.module.ts
    
    ...
    import { IgxListModule } from 'igniteui-angular/list';
    import { IgxAvatarModule } from 'igniteui-angular/avatar';
    import { IgxBadgeModule } from 'igniteui-angular/badge';
    // import { IgxListModule, IgxAvatarModule, IgxBadgeModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxListModule, IgxAvatarModule, IgxBadgeModule],
    })
    export class AppModule {}
    
    Note

    The igx-badge has icon and type inputs to configure the badge look. You can set the icon by providing its name from the official material icons set. The badge type can be set to either default, info, success, warning, or error. Depending on the type, a specific background color is applied.

    In our sample, icon and type are bound to model properties named icon and type.

    A continuación, agregamos los contactos en nuestra plantilla:

    <!-- contacts.component.html -->
    
    <igx-list>
      <igx-list-item isHeader="true">
        Team Members (4)
      </igx-list-item>
      <igx-list-item *ngFor="let member of members">
        <div class="wrapper">
          <div>
            <igx-avatar icon="person" shape="circle" size="small"></igx-avatar>
            <igx-badge [icon]="member.icon" [type]="member.type" class="badge-style"></igx-badge>
          </div>
          <div class="contact-container">
            <span class="contact-name">{{ member.name }}</span>
          </div>
        </div>
      </igx-list-item>
    </igx-list>
    

    Vamos a crear nuestros miembros en el archivo mecanografiado de esta manera:

    // contacts.component.ts
    
    ...
     public members: Member[] = [
        new Member('Terrance Orta', 'online'),
        new Member('Donna Price', 'online'),
        new Member('Lisa Landers', 'away'),
        new Member('Dorothy H. Spencer', 'offline'),
      ];
    
    
    
    ...
    class Member {
        public name: string;
        public status: string;
        public type: string;
        public icon: string;
    
        constructor(name: string, status: string) {
            this.name = name;
            this.status = status;
            switch (status) {
                case 'online':
                    this.type = 'success';
                    this.icon = 'check';
                    break;
                case 'away':
                    this.type = 'warning';
                    this.icon = 'schedule';
                    break;
                case 'offline':
                    this.type = 'error';
                    this.icon = 'remove';
                    break;
            }
        }
    }
    

    Coloque la insignia en su contenedor principal:

    /* contacts.component.css */
    
    .wrapper {
        display: flex;
        flex-direction: row;
    }
    
    .contact-name {
        font-weight: 600;
    }
    
    .contact-container {
        margin-left: 20px;
    }
    
    .badge-style {
      position: absolute;
      bottom: 2.5px;
      left: 40px;
    }
    
    

    Si la muestra está configurada correctamente, se debe mostrar una lista de miembros y cada miembro tiene un avatar y una insignia que muestra su estado actual.

    Estilismo

    Badge Theme Property Map

    Changing the $background-color property automatically updates the following dependent properties:

    Propiedad principal Propiedad dependiente Descripción
    $background color $icon color El color usado para los iconos en la insignia.
    $text-color El color que se usa para el texto en la insignia.

    To get started with styling the badges, we need to import the index file, where all the theme functions and component mixins live:

    @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 badge-theme and accepts some parameters that style the badge's items. When you set the $background-color, the $icon-color and $text-color are automatically assigned based on which offers better contrast—black or white. Note that the $border-radius property only takes effect when the badge's shape is set to square.

    $custom-badge-theme: badge-theme(
      $background-color: #57a5cd,
      $border-radius: 4px
    );
    

    To include the new theme we use the css-vars mixin:

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

    Demo

    Styling with Tailwind

    You can style the badge using our custom Tailwind utility classes. Make sure to set up Tailwind first.

    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';
    

    The utility file includes both light and dark theme variants.

    • Use light-* classes for the light theme.
    • Use dark-* classes for the dark theme.
    • Append the component name after the prefix, e.g., light-badge, dark-badge.

    Once applied, these classes enable dynamic theme calculations. From there, you can override the generated CSS variables using arbitrary properties. After the colon, provide any valid CSS color format (HEX, CSS variable, RGB, etc.).

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

    <igx-badge
    class="!light-badge ![--background:#FF4E00] ![--border-radius:4px]">
    </igx-badge>
    
    Note

    The exclamation mark(!) is required to ensure the utility class takes precedence. Tailwind applies styles in layers, and without marking these styles as important, they will get overridden by the component’s default theme.

    Al final, tus insignias deberían verse así:

    API References

    Theming Dependencies

    Additional Resources

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