Visão geral do componente Angular Button Group

    O componente Angular Button Group é usado para organizar botões em grupos de botões estilizados com alinhamento horizontal/vertical, seleção única/múltipla e alternância.

    Angular Button Group Example

    Getting Started with Ignite UI for Angular Button Group

    Para começar a usar o componente Ignite UI for Angular Button Group, 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.

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

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

    Alternatively, as of 16.0.0 you can import the IgxButtonGroupComponent as a standalone dependency, or use the IGX_BUTTON_GROUP_DIRECTIVES token to import the component and all of its supporting components and directives.

    // home.component.ts
    
    ...
    import { IGX_BUTTON_GROUP_DIRECTIVES, IgxIconComponent } from 'igniteui-angular';
    // import { IGX_BUTTON_GROUP_DIRECTIVES, IgxIconComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-buttongroup>
            <button igxButton>
                <igx-icon>format_align_left</igx-icon>
            </button>
            <button igxButton>
                <igx-icon>format_align_center</igx-icon>
            </button>
            <button igxButton>
                <igx-icon>format_align_right</igx-icon>
            </button>
            <button igxButton selected>
                <igx-icon>format_align_justify</igx-icon>
            </button>
        </igx-buttongroup>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_BUTTON_GROUP_DIRECTIVES, IgxIconComponent]
        /* or imports: [IgxButtonGroupComponent, IgxButtonDirective, IgxIconComponent] */
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Button Group module or directives imported, you can start with a basic configuration of the igx-buttongroup and its buttons.

    Using for Angular Button Group Component

    Add Button Group

    Use the igx-buttongroup selector to wrap your buttons and display them into a button group. If you want a button to be selected by default, use the selected property:

    <!-- sample.component.html -->
    <igx-buttongroup>
      <button igxButton>
        <igx-icon>format_align_left</igx-icon>
      </button>
      <button igxButton>
        <igx-icon>format_align_center</igx-icon>
      </button>
      <button igxButton>
        <igx-icon>format_align_right</igx-icon>
      </button>
      <button igxButton selected>
        <igx-icon>format_align_justify</igx-icon>
      </button>
    </igx-buttongroup>
    

    Examples

    Alignment

    Use the alignment input property to set the orientation of the buttons in the button group.

    //sample.component.ts
    import { ButtonGroupAlignment } from 'igniteui-angular';
    // import { ButtonGroupAlignment } from '@infragistics/igniteui-angular'; for licensed package
    
    ...
    public alignment = ButtonGroupAlignment.vertical;
    ...
    
    <!-- sample.component.html -->
    <igx-buttongroup [alignment]="alignment">
      <button igxButton>Sofia</button>
      <button igxButton>London</button>
      <button igxButton selected>New York</button>
      <button igxButton>Tokyo</button>
    </igx-buttongroup>
    

    Escolha

    In order to configure the igx-buttongroup selection, you could use its selectionMode property. This property accepts the following three modes:

    • single- modo de seleção padrão do grupo de botões. Um único botão pode ser selecionado/desselecionado pelo usuário.
    • singleRequired- imita um comportamento de grupo de rádio. Apenas um botão pode ser selecionado e, uma vez feita a seleção inicial, a desmarcação não é possível por meio da interação do usuário.
    • multi- vários botões no grupo podem ser selecionados e desmarcados.

    The sample below demonstrates the exposed igx-buttongroup selection modes:

    Tamanho

    The --ig-size CSS custom property can be used to control the size of the button group.

    /* sample.component.scss */
    igx-buttongroup {
      --ig-size: var(--ig-size-small);
    }
    
    <!-- sample.component.html -->
    <igx-buttongroup></igx-buttongroup>
    

    Custom toggle buttons

    Use the values input property to set an array of customized buttons in the button group.

    // sample.component.ts
    
    interface IButton {
        ripple?: string;
        label?: string;
        disabled?: boolean;
        togglable?: boolean;
        selected?: boolean;
        color?: string;
        icon?: string;
    }
    
    class ToggleButton {
        private ripple: string;
        private label: string;
        private disabled: boolean;
        private togglable: boolean;
        private selected: boolean;
        private color: string;
        private icon: string;
    
        constructor(obj?: IButton) {
            this.ripple = obj.ripple || 'gray';
            this.label = obj.label;
            this.selected = obj.selected || false;
            this.togglable = obj.togglable || true;
            this.disabled = obj.disabled || false;
            this.color = obj.color;
            this.icon = obj.icon;
        }
    }
    ...
    public bordersButtons: ToggleButton[];
    
    public ngOnInit() {
        this.bordersButtons = [
            new ToggleButton({
                icon: 'border_top',
                selected: true
            }),
            new ToggleButton({
                icon: 'border_right',
                selected: false
            }),
            new ToggleButton({
                icon: 'border_bottom',
                selected: false
            }),
            new ToggleButton({
                icon: 'border_left',
                selected: false
            })
        ];
    }
    ...
    
    <!-- sample.component.html -->
    <igx-buttongroup [selectionMode]="'multi'" [values]="bordersButtons"></igx-buttongroup>
    

    Estilização

    Button Group Theme Property Map

    When you set a value for the $item-background property, all related dependent properties listed in the table below are automatically updated to maintain visual consistency. The table shows which properties are affected when you customize the primary property.

    Propriedade primária Propriedade dependente Descrição
    $item-contexto
    $item-hover-background A cor de fundo flutuante para os itens.
    $item-selecionado-fundo A cor de fundo do item selecionado.
    $item-foco-foco-o-fundo A cor de fundo do item focada.
    $disabled-cor de fundo A cor de fundo do item desativada.
    $item-cor da borda A cor da borda dos itens.
    $item-text-color A cor do texto para os itens.
    $idle-sombra-cor A cor da sombra ociosa para os itens.
    $item-hover-background
    $item-selecionada-passa-mouse-fundo O item selecionado passa a cor de fundo com o curso.
    $item-fundo-focado no hover A cor de fundo flutuante focada.
    $item-hover-text-color A cor do texto para itens flutuados.
    $item-homover-ícone-cor A cor do ícone para itens flutuados.
    $item-selecionado-fundo
    $item-foco-selecionado-fundo-fundo O item selecionado foca a cor de fundo.
    $disabled-selecionado-fundo A cor de fundo selecionada para deficientes.
    $item-selecionada-cor-texto- A cor do texto para itens selecionados.
    $item-icon-color-selecionado A cor do ícone para itens selecionados.
    $item-selecionada-passar o curso-de-texto-cor A cor do texto para itens selecionados flutua.
    $item-escolhido-ícone-color-passar o mouse A cor do ícone para itens selecionados flutuando.
    $item-cor da borda
    $item-borda-cor flutuante A cor da borda para itens flutuados.
    $item-foca-no-cor-de-borda A cor da borda para itens focados.
    $item-selecionada-cor-borda- A cor da borda para itens selecionados.
    $item-selecionada-flutuar-cor-borda- A cor da borda para itens selecionados de flutuação.
    $item-fronteira para pessoas com deficiência A cor da borda para itens desativados.
    $disabled-selecionada-cor-borda- A cor da borda para itens selecionados desativados.

    To get started with styling the button group, 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 button-group-theme and specifying just the $item-background. Based on this value, the theme will automatically compute appropriate state colors, contrast foregrounds, and borders for the button group. Of course, you're still free to override any of the theme parameters with custom values if needed.

    $custom-button-group: button-group-theme(
      $item-background: #57a5cd,
    );
    

    As seen, the button-group-theme exposes some useful parameters for basic styling of its items. If you want to drill deeper and change some button specific parameters, you can create a new theme that extends the button-theme and scope it under the respective button group class.

    A última etapa é incluir o tema do componente.

    @include css-vars($custom-button-group);
    

    Demo

    Styling with Tailwind

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

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

    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-button-group, dark-button-group.

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

    Você pode encontrar a lista completa de propriedades no tema do grupo de botões. A sintaxe é a seguinte:

    <igx-button-group
    class="!light-button-group ![--item-background:#7B9E89]"
    >
    ...
    </igx-button-group>
    
    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.

    No final, seu grupo de botões deve ficar assim:

    API References

    Theming Dependencies

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.