Visão geral do componente do chip Angular

    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 começar a usar o componente Ignite UI for Angular Chip, primeiro você precisa instalar Ignite UI for Angular. Em um aplicativo Angular existente, digite o seguinte comando:

    ng add igniteui-angular
    

    Para obter uma introdução completa ao Ignite UI for Angular, leia o tópico de introdução.

    O próximo passo é importar o IgxChipsModule no arquivo 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 você pode importarIgxChipComponent como uma dependência independente ou usar oIGX_CHIPS_DIRECTIVES token para importar o componente e todos os seus componentes e diretivas de suporte.

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

    Escolha

    Selecionando o Padrão

    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

    Remoção do Padrão

    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.

    Por padrão, o chip não é removido automaticamente da árvore DOM ao clicar no ícone remover. A remoção precisa ser feita 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();
    }
    

    Arrastando

    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 criar o exemplo de demonstração, usaremos os recursos acima:

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

    Se tudo correr bem, você deverá ver isto no seu 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:

    Prefixo e Sufixo do 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:

    Densidade de Chips
    <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.

    Selecionando 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.

    Remover ícones
    <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 criar o exemplo de demonstração abaixo, usaremos os recursos acima:

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

    Se tudo correr bem, você deverá ver isto no seu navegador:

    Chip Area

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

    Reorder Chips

    Arrastando

    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 do teclado quando o chip está em foco:

      • ESQUERDA- Move o foco para o chip à esquerda.

        Tecla Esquerda da Seta
      • DIREITA- Move o foco para o chip à direita.

        Tecla Direita da Seta
      • ESPAÇO- Alterna a seleção de chip, se possível.

        Chave de Espaço
      • 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 do teclado quando o botão Remover está em foco:

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

    Aqui está um exemplo da área de chips usando IgxAvatar como prefixo e ícones personalizados para todos os 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>
    

    Redimensione o avatar para caber no 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://pt-br.infragistics.com/angular-demos/assets/images/men/27.jpg'
        },
        {
            id: '423-676-2869',
            name: 'Richard Mahoney',
            photo: 'https://pt-br.infragistics.com/angular-demos/assets/images/men/13.jpg'
        },
        {
            id: '859-496-2817',
            name: 'Donna Price',
            photo: 'https://pt-br.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;
    }
    

    Se tudo estiver configurado corretamente, você deverá ver isto no seu navegador:

    Demo

    Estilização

    Chip Theme Property Map

    Quando você modifica uma propriedade primária, todas as propriedades dependentes relacionadas são atualizadas automaticamente:

    Propriedade primária Propriedade dependente Descrição
    $background
    $text-cor A cor do texto do chip.
    $border cor A cor da borda do chip.
    $hover-contexto O chip paira na cor de fundo.
    $hover-cor-borda A cor da borda do chip paira.
    $hover-cor-texto O chip paira cor do texto.
    $focus-contexto A cor de fundo do foco do chip.
    $selected-contexto O chip selecionou a cor de fundo.
    $focus-contexto
    $focus-cor-texto A cor de foco do texto do chip.
    $focus-cor da borda A cor da borda do foco do chip.
    $focus-outline-color (apenas variantes bootstrap e índigo) A cor do contorno do foco do chip.
    $selected-contexto
    $selected-cor-texto A cor do texto do chip selecionada.
    $selected-cor-borda A cor selecionada da borda do chip.
    $hover-selecionado-fundo O chip selecionado passa a cor de fundo do lugar.
    $hover-selecionado-fundo
    $hover-texto-selecionado-color- O chip selecionado passou a cor do texto do curso.
    $hover-cor-borda-selecionada O chip selecionado paira na cor da borda.
    $focus-selecionado-fundo A cor de fundo de foco do chip selecionada.
    $focus-selecionado-fundo
    $focus-cor-texto-selecionado O texto do chip selecionado foca a cor.
    $focus-selecionada-cor-borda- A cor da borda de foco do chip selecionada.
    $focus-selecionada-outline-color (apenas variantes bootstrap e índigo) O chip foca a cor do contorno no estado selecionado.

    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,
    );
    

    Por fim, inclua o tema personalizado em seu aplicativo:

    @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

    Você pode estilizar o chip usando nossas classes utilitárias personalizadas Tailwind. Certifique-se de configurar o Tailwind primeiro.

    Junto com a importação de vento de cauda em sua folha de estilo global, você pode aplicar os utilitários de tema desejados da seguinte maneira:

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

    O arquivo utilitário inclui tantolight as variantes quantodark as do tema.

    • Uselight-* as aulas para o tema da luz.
    • Usedark-* classes para o tema sombrio.
    • Adicione o nome do componente após o prefixo, por exemplo,light-chip,dark-chip.

    Uma vez aplicadas, essas classes possibilitam cálculos dinâmicos de temas. A partir daí, você pode sobrescrever as variáveis CSS geradas usandoarbitrary properties. Após os dois-pos, forneça qualquer formato de cor CSS válido (HEX, variável CSS, RGB, etc.).

    Você pode encontrar a lista completa de propriedades no tema do chip. A sintaxe é a seguinte:

    <igx-chip
      class="!light-chip
      ![--background:#99BAA6]
      ![--remove-icon-color:#C92828]"
      ...
    >
      {{chip.text}}
    </igx-chip>
    
    Note

    O ponto de exclamação(!) é necessário para garantir que a classe utilitária tenha prioridade. O Tailwind aplica estilos em camadas e, sem marcar esses estilos como importantes, eles serão substituídos pelo tema padrão do componente.

    No final, seus chips devem ficar assim:

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

    Saiba mais sobre isso no artigo Tamanho.

    API

    Theming Dependencies

    References

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.