Descripción general de los componentes de Angular Chip

    The Angular Chip component is a visual element that displays information in an oval container. The component has various properties - it can be templated, deleted, and selected. Multiple chips can be reordered and visually connected to each other, using the chip area as a container.

    Angular Chip Example

    Getting Started with Ignite UI for Angular Chip

    Para comenzar con el componente Ignite UI for Angular Chip, 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 importar IgxChipsModule en el archivo app.module.ts:

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

    Alternativamente,16.0.0 puedes importarlosIgxChipComponent como una dependencia independiente, o usar elIGX_CHIPS_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.

    // home.component.ts
    
    import { IGX_CHIPS_DIRECTIVES } from 'igniteui-angular/chips';
    import { NgFor } from '@angular/common';
    // import { IGX_CHIPS_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
      selector: 'app-home',
      template: `
        <igx-chip *ngFor="let chip of chipList" [id]="chip.id">
          {{ chip.text }}
        </igx-chip>
      `,
      styleUrls: ['home.component.scss'],
      standalone: true,
      imports: [IGX_CHIPS_DIRECTIVES, NgFor],
    })
    export class HomeComponent {
      public chipList = [
        { text: 'Country', id: '1', icon: 'place' },
        { text: 'City', id: '2', icon: 'location_city' },
        { text: 'Address', id: '3', icon: 'home' },
        { text: 'Street', id: '4', icon: 'streetview' },
      ];
    }
    

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

    Using the Angular Chip Component

    The IgxChipComponent has an id input property so that the different chip instances can be easily distinguished. If an id is not provided, it will be automatically generated.

    <igx-chip *ngFor="let chip of chipList" [id]="chip.id">
      {{chip.text}}
    </igx-chip>
    

    Selección

    Selección de predeterminado

    Selection can be enabled by setting the selectable input property to true. When selecting a chip, the selectedChanging event is fired. It provides the new selected value so you can get the new state and the original event in originalEvent that triggered the selection change. If this is not done through user interaction but instead is done by setting the selected property programmatically, the originalEvent argument has a value of null.

    <igx-chip *ngFor="let chip of chipList" [selectable]="true">
      <igx-icon igxPrefix>{{chip.icon}}</igx-icon>
      {{chip.text}}
    </igx-chip>
    

    Removing

    Eliminación del predeterminado

    Removing can be enabled by setting the removable input to true. When enabled, a remove button is rendered at the end of the chip. When removing a chip, the remove event is emitted.

    De forma predeterminada, el chip no se elimina automáticamente del árbol DOM al hacer clic en el icono de eliminación. La eliminación debe realizarse manualmente.

    <igx-chip *ngFor="let chip of chipList" [id]="chip.id" [removable]="true" (remove)="chipRemoved($event)">
      <igx-icon igxPrefix>{{chip.icon}}</igx-icon>
      {{chip.text}}
    </igx-chip>
    
    public chipRemoved(event: IBaseChipEventArgs) {
        this.chipList = this.chipList.filter((item) => {
            return item.id !== event.owner.id;
        });
        this.changeDetectionRef.detectChanges();
    }
    

    Arrastrando

    Dragging can be enabled by setting the draggable input to true. When enabled, you can click and drag the chip around.

    <igx-chip *ngFor="let chip of chipList" [id]="chip.id" [draggable]="true">
      <igx-icon igxPrefix>{{chip.icon}}</igx-icon>
      {{chip.text}}
    </igx-chip>
    
    Note

    To reorder the chips you need to handle the event using the IgxChipsAreaComponent.

    Para crear la muestra de demostración, utilizaremos las funciones anteriores:

    <igx-chip *ngFor="let chip of chipList" [id]="chip.id" [selectable]="true" [removable]="true" (remove)="chipRemoved($event)">
      <igx-icon igxPrefix>{{chip.icon}}</igx-icon>
       {{chip.text}}
    </igx-chip>
    

    Then, we need to add the chipList and the function, that handles the remove event:

    import { IBaseChipEventArgs } from 'igniteui-angular/chips';
    // import { IBaseChipEventArgs } from '@infragistics/igniteui-angular'; for licensed package
    ...
    public chipList = [
        {
            text: 'Country',
            id: '1',
            icon: 'place'
        },
        {
            text: 'City',
            id: '2',
            icon: 'location_city'
        },
        {
            text: 'Town',
            id: '3',
            icon: 'store'
        },
        {
            text: 'First Name',
            id: '4',
            icon: 'person_pin'
        }
    ];
    
    private changeDetectionRef: any;
    
    public chipRemoved(event: IBaseChipEventArgs) {
        this.chipList = this.chipList.filter((item) => {
            return item.id !== event.owner.id;
        });
        this.changeDetectionRef.detectChanges();
    }
    

    Si todo ha ido bien deberías ver esto en tu navegador:

    Chip Templates

    All of the IgxChipComponent's elements are templatable.

    You can template the prefix and the suffix of the chip, using the IgxPrefix and the IgxSuffix directives:

    Prefijo y sufijo del chip
    <igx-chip>
      <igx-icon igxPrefix>insert_emoticon</igx-icon>
      <igx-icon igxSuffix style="transform: rotate(180deg)">insert_emoticon</igx-icon>
      <span>Why not both?</span>
    </igx-chip>
    

    You can customize the size of the chip, using the [--ig-size] CSS variable. By default it is set to var(--ig-size-large). It can also be set to var(--ig-size-medium) or var(--ig-size-small), while everything inside the chip retains its relative positioning:

    Densidad de virutas
    <igx-chip>Hi! My name is Chip!</igx-chip>
    
    <igx-chip style="--ig-size: var(--ig-size-medium)">
      I can be smaller!
    </igx-chip>
    
    <igx-chip style="--ig-size: var(--ig-size-small)">
      <igx-icon igxPrefix>child_care</igx-icon>
      Even tiny!
    </igx-chip>
    

    You can customize the select icon, using the selectIcon input. It accepts values of type TemplateRef and overrides the default icon while retaining the same functionality.

    Selección de personalizados
    <igx-chip *ngFor="let chip of chipList" [selectable]="true" [selectIcon]="mySelectIcon">
      <igx-icon igxPrefix>{{chip.icon}}</igx-icon>
      {{chip.text}}
    </igx-chip>
    
    <ng-template #mySelectIcon>
      <igx-icon>check_circle</igx-icon>
    </ng-template>
    

    You can customize the remove icon, using the removeIcon input. It takes a value of type TemplateRef and renders it instead of the default remove icon.

    Eliminar iconos
    <igx-chip *ngFor="let chip of chipList" [removable]="true" [removeIcon]="myRemoveIcon">
      <igx-icon igxPrefix>{{chip.icon}}</igx-icon>
      {{chip.text}}
    </igx-chip>
    
    <ng-template #myRemoveIcon>
      <igx-icon>delete</igx-icon>
    </ng-template>
    

    Demo

    Para crear el ejemplo de demostración a continuación, usaremos las funciones anteriores:

    <igx-chip
    *ngFor="let chip of chipList"
    [id]="chip.id"
    [selectable]="true"
    [removable]="true"
    (remove)="chipRemoved($event)"
    >
        <igx-icon igxPrefix>{{chip.icon}}</igx-icon>
        {{chip.text}}
    </igx-chip>
    

    Then, we need to add the chipList and the function, that handles the remove event:

    import { IBaseChipEventArgs } from 'igniteui-angular/chips';
    // import { IBaseChipEventArgs } from '@infragistics/igniteui-angular'; for licensed package
    ...
    public chipList = [
        {
            text: 'Country',
            id: '1',
            icon: 'place'
        },
        {
            text: 'City',
            id: '2',
            icon: 'location_city'
        },
        {
            text: 'Town',
            id: '3',
            icon: 'store'
        },
        {
            text: 'First Name',
            id: '4',
            icon: 'person_pin'
        }
    ];
    
    private changeDetectionRef: any;
    
    public chipRemoved(event: IBaseChipEventArgs) {
        this.chipList = this.chipList.filter((item) => {
            return item.id !== event.owner.id;
        });
        this.changeDetectionRef.detectChanges();
    }
    

    Si todo ha ido bien deberías ver esto en tu navegador:

    Chip Area

    The IgxChipsAreaComponent is used when handling more complex scenarios that require interaction between chips (dragging, selection, navigation, etc.).

    Reorder Chips

    Arrastrando

    The chip can be dragged by the end-user in order to change its position. The dragging is disabled by default but can be enabled using the draggable input property. You need to handle the actual chip reordering manually. This is where the chip area comes in handy since it provides the reorder event that returns the new order when a chip is dragged over another chip.

    <igx-chips-area (reorder)="chipsOrderChanged($event)">
      <igx-chip *ngFor="let chip of chipList" [draggable]="'true'">
        <igx-icon igxPrefix>{{chip.icon}}</igx-icon>
        {{chip.text}}
      </igx-chip>
    </igx-chips-area>
    
    public chipsOrderChanged(event: IChipsAreaReorderEventArgs) {
        const newChipList = [];
        for (const chip of event.chipsArray) {
            const chipItem = this.chipList.filter((item) => {
                return item.id === chip.id;
            })[0];
            newChipList.push(chipItem);
        }
        this.chipList = newChipList;
    }
    

    Keyboard Navigation

    The chip can be focused using the Tab key or by clicking on it. When the chips are in a chip area, they can be reordered using keyboard navigation:

    • Controles del teclado cuando el chip está enfocado:

      • IZQUIERDA: mueve el foco al chip de la izquierda.

        Flecha Izquierda
      • DERECHA: mueve el foco al chip de la derecha.

        Flecha de tecla derecha
      • ESPACIO: alterna la selección de chip si es seleccionable.

        Clave de espacio
      • DELETE - Triggers the remove event for the igxChip so the chip deletion can be handled manually.

      • SHIFT + LEFT - Triggers reorder event for the igxChipArea when the currently focused chip should move position to the left.

      • SHIFT + RIGHT - Triggers reorder event for the igxChipArea when the currently focused chip should move one position to the right.

    • Controles del teclado cuando el botón Quitar está enfocado:

      • SPACE or ENTER Fires the remove output so the chip deletion can be handled manually.

    Aquí hay un ejemplo del área del chip usando IgxAvatar como prefijo e íconos personalizados para todos los chips:

    <igx-chips-area (reorder)="chipsOrderChanged($event)">
      <igx-chip
        *ngFor="let chip of chipList"
        [id]="chip.id"
        [selectable]="true"
        [selectIcon]="mySelectIcon"
        [removable]="true"
        [removeIcon]="myRemoveIcon"
        (remove)="chipRemoved($event)"
        [draggable]="'true'">
        <igx-avatar
          class="chip-avatar-resized"
          igxPrefix
          [src]="chip.photo"
          shape="circle">
        </igx-avatar>
        {{chip.name}}
      </igx-chip>
    </igx-chips-area>
    
    <ng-template #mySelectIcon>
      <igx-icon>check_circle</igx-icon>
    </ng-template>
    
    <ng-template #myRemoveIcon>
      <igx-icon>delete</igx-icon>
    </ng-template>
    

    Cambie el tamaño del avatar para que se ajuste al chip:

    .chip-avatar-resized {
      width: 2em;
      height: 2em;
      min-width: 2em;
    }
    

    Add the chipList and the functions that handle the events:

    import { IBaseChipEventArgs, IChipsAreaReorderEventArgs } from 'igniteui-angular/chips';
    // import { IBaseChipEventArgs, IChipsAreaReorderEventArgs } from '@infragistics/igniteui-angular'; for licensed package
    
    ...
    public chipList = [
        {
            id: '770-504-2217',
            name: 'Terrance Orta',
            photo: 'https://es.infragistics.com/angular-demos/assets/images/men/27.jpg'
        },
        {
            id: '423-676-2869',
            name: 'Richard Mahoney',
            photo: 'https://es.infragistics.com/angular-demos/assets/images/men/13.jpg'
        },
        {
            id: '859-496-2817',
            name: 'Donna Price',
            photo: 'https://es.infragistics.com/angular-demos/assets/images/women/50.jpg'
        }
    ];
    
    private changeDetectionRef: any;
    
    public chipRemoved(event: IBaseChipEventArgs) {
        this.chipList = this.chipList.filter((item) => {
            return item.id !== event.owner.id;
        });
        this.changeDetectionRef.detectChanges();
    }
    
    public chipsOrderChanged(event: IChipsAreaReorderEventArgs) {
        const newChipList = [];
        for (const chip of event.chipsArray) {
            const chipItem = this.chipList.filter((item) => {
                return item.id === chip.id;
            })[0];
            newChipList.push(chipItem);
        }
        this.chipList = newChipList;
    }
    

    Si todo está configurado correctamente, deberías ver esto en tu navegador:

    Demo

    Estilismo

    Chip Theme Property Map

    Cuando modificas una propiedad primaria, todas las propiedades dependientes relacionadas se actualizan automáticamente:

    Propiedad principal Propiedad dependiente Descripción
    $background
    $text-color El color del texto del chip.
    $border color El color del borde de la viña.
    $hover antecedentes El chip flota color de fondo.
    $hover-color de borde El chip flota el color del borde del curso.
    $hover-text-color El chip flota color de texto.
    $focus-antecedentes El color de fondo del enfoque en chip.
    $selected antecedentes El chip seleccionó el color de fondo.
    $focus-antecedentes
    $focus-text-color El texto del chip enfoca color.
    $focus-color de borde El color del borde del enfoque del chip.
    $focus-contorno-color (solo variantes bootstrap y añígo) El enfoque del chip delinea el color.
    $selected antecedentes
    $selected-text-color El color de texto del chip seleccionado.
    $selected-color del borde El color de borde seleccionado del chip.
    $hover-selección de antecedentes El chip seleccionado flota en el color de fondo.
    $hover-selección de antecedentes
    $hover-color-texto-seleccionado El chip seleccionado flota color de texto.
    $hover-color-borde-seleccionado El chip seleccionado flota con el color del borde.
    $focus-seleccionado-fondo El chip seleccionado enfoca el color de fondo.
    $focus-seleccionado-fondo
    $focus-color-texto-seleccionado El texto del chip seleccionado enfoca el color.
    $focus-color-borde-seleccionado El chip seleccionado enfoca el color del borde.
    $focus-selecto-contorno-color (solo variantes bootstrap e índigo) El chip enfoca el color del contorno en el estado seleccionado.

    To get started with styling the chip, 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 chip-theme and accepts some parameters that style the chip's items. By specifying the $background or the $selected-background, the theme automatically calculates appropriate state colors and contrast foregrounds. You can still override any other parameter with custom values as needed.

    $custom-chip-theme: chip-theme(
        $background: #57a5cd,
        $selected-background: #ecaa53,
        $remove-icon-color: #d81414,
        $border-radius: 5px,
    );
    

    Finalmente, incluya el tema personalizado en su aplicación:

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

    In the sample below, you can see how using the chip component with customized CSS variables allows you to create a design that visually resembles the chip used in the Ant design system.

    Styling with Tailwind

    Puedes diseñar el chip 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-chip,dark-chip.

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

    <igx-chip
      class="!light-chip
      ![--background:#99BAA6]
      ![--remove-icon-color:#C92828]"
      ...
    >
      {{chip.text}}
    </igx-chip>
    
    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, tus chips deberían verse así:

    Custom sizing

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

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

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

    <div class="my-app">
      <igx-chip></igx-chip>
    </div>
    
    .my-app {
      --igx-chip-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-chip {
      --ig-size: var(--ig-size-small);
    }
    

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

    API

    Theming Dependencies

    References

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