Descripción general del componente Icono Angular

    El componente Ignite UI for Angular Icon unifica las familias de iconos/fuentes para que los desarrolladores puedan utilizarlas indistintamente y añadir iconos de material al marcado.

    Angular Icon Example

    Getting Started with Ignite UI for Angular Icon

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

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

    Alternativamente,16.0.0 puedes importarlosIgxIconComponent como una dependencia independiente.

    // home.component.ts
    
    import { IgxIconComponent } from 'igniteui-angular/icon';
    // import { IgxIconComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
      selector: 'app-home',
      template: '<igx-icon [style.color]="color">home</igx-icon>',
      styleUrls: ['home.component.scss'],
      standalone: true,
      imports: [IgxIconComponent],
    })
    export class HomeComponent {
      public color = '#e41c77';
    }
    

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

    Using the Angular Icon

    Icon Color

    Use style.color CSS property to change its default color:

    <igx-icon [style.color]="#e41c77">home</igx-icon>
    

    Inactive Icon

    If you want to disable an icon, you can use the active property:

    <igx-icon [active]="false">volume_off</igx-icon>
    

    Content Projection

    Puedes configurar íconos con proyección de contenido:

    <igx-icon>bluetooth</igx-icon>
    

    Icon Size

    You can customize the icons using CSS. To change an icon size use the --size CSS variable:

    .custom-size {
      --size: 56px;
    }
    

    SVG Icons

    You can also use an SVG image as an icon. First, inject the IgxIconService dependency. In this example we will inject it in a component's constructor but you can use it wherever it is needed in your code.

    Use the addSvgIcon method to import the SVG file in cache. When the SVG is cached, it can be used anywhere in the application. The icon name and file URL path are the method's mandatory parameters; family can be specified as well. After that, you can use the SVG files in the HTML markup. Alternatively, you can use the addSvgIconFromText method to import an SVG file, providing the SVG text content instead of the file URL.

    • Tenga en cuenta que si hay dos iconos con el mismo nombre y la misma familia, el icono SVG se mostrará con prioridad.
    • Es mejor no proporcionar el ancho y el alto de la imagen en el archivo SVG.
    • Es posible que necesite scripts de polyfill adicionales ("polyfills") para Internet Explorer.
    constructor(private iconService: IgxIconService) { }
    
    public ngOnInit() {
        // register custom SVG icons
        this.iconService.addSvgIcon('contains', '/assets/images/svg/contains.svg', 'filter-icons');
    }
    
    <igx-icon name="contains" family="filter-icons"></igx-icon>
    

    Material Symbols

    Additionally, users can take advantage of the latest Material icons and their design variations included in the newly created Material Symbols Library. To start using Material Symbols, first you have to add the library to your application:

    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" rel="stylesheet"/>
    

    Then we need to inject the IgxIconService dependency and make use of its setFamily method so that Material Symbols can work with igx-icon:

    constructor(private iconService: IgxIconService) { }
    
    public ngOnInit() {
        // registers a 'material-symbols-outlined' class to be applied to all igx-icons with 'material-symbols' font-family
        this.iconService.setFamily('material-symbols', { className: 'material-symbols-outlined', type: 'liga' });
    }
    

    Ahora estamos listos para agregar el ícono deseado a nuestro marcado y personalizarlo usando estilos de fuente ajustables:

    <igx-icon family="material-symbols" name="diamond" class="custom-icon"></igx-icon>
    
    .custom-icon {
      font-variation-settings: "FILL" 0, "wght" 200, "GRAD" 0, "opsz" 40;
    }
    

    To learn more about Material Symbols styles please visit their official documentation.

    Server-side Rendering Note

    Note

    In case you have implemented server side rendering logic in your application using Angular Universal and have used the IgxIconService to register icons, this may cause the following exception:

    > XMLHttpRequest is not defined. Could not fetch SVG from url. >

    In order to avoid this, execute the listed steps:

    1. Instale `xmlhttprequest`:
      npm i xmlhttprequest
      
    2. En la parte superior de su archivo `server.ts`, agregue:
      (global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
      

    Estilismo

    To get started with styling the icons, 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 icon-theme and accepts the parameters, required to customize the icon as desired.

    $custom-icon-theme: icon-theme(
      $color: #1481b8,
      $disabled-color: #494949,
    );
    

    El último paso es pasar el tema de ícono personalizado en nuestra aplicación:

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

    Demo

    SVG Limitations

    It’s important to note that when using custom SVG icons, the icon-theme can apply and overwrite colors only on the <svg> element itself. If the SVG contains child elements such as <path>, <rect>, <circle>, <g>, etc., with hardcoded color values, those colors cannot be overridden by the theme.

    Por ejemplo:

    <svg>
        <path fill="#050d42"/>
    </svg>
    

    In this case, the icon will always use the #050d42 color defined in the <path>, regardless of the color provided by the theme.

    <svg fill="#050d42">
        <path .../>
    </svg>
    

    Here, the fill color is applied to the <svg> element, so it can be overridden with custom color provided via icon-theme.

    We recommend not using hardcoded colors on SVG child elements so the icon can be styled entirely using the icon-theme. However, if you still want to apply hardcoded colors to child elements, you can also use the Ignite UI color variables.

    <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
      <!-- This element uses the theme color from the igx-icon component -->
      <path d="M12 2L15 8H9L12 2Z" />
    
      <!-- This element uses an accent color from Ignite UI palette -->
      <circle cx="12" cy="17" r="4" fill="var(--ig-primary-500)" />
    </svg>
    

    Custom sizing

    You can either use the --size variable, targeting the igx-icon directly:

    igx-icon {
      --size: 50px;
    }
    

    Or you can use the universal --igx-icon-size variable to target all instances:

    <div class="my-app">
      <igx-icon></igx-icon>
    </div>
    
    .my-app {
      --igx-icon-size: 50px;
    }
    

    You can also use one of the predefined sizes, assigning it to the --ig-size variable. The available values for --ig-size are --ig-size-small, --ig-size-medium, and --ig-size-large:

    igx-icon {
      --ig-size: var(--ig-size-medium);
    }
    

    Obtén más información al respecto en el artículo Talla.

    Styling with Tailwind

    Puedes decorarlosicon 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-icon,dark-icon.

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

    <igx-icon class="!light-icon ![--color:#7B9E89] ![--size:48px]">person</igx-icon>
    
    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 icono debería verse así:

    API References

    Additional Resources

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