Visão geral do componente Angular Select

    Angular Select é um componente de formulário usado para selecionar um único valor de uma lista de valores predefinidos. O Angular Select Component fornece funcionalidade idêntica ao elemento select HTML nativo, mas oferece muito mais opções de personalização. Ele é baseado no IgxDropDownComponent e suporta todos os seus recursos, incluindo modelagem, virtualização e personalização dos itens da lista suspensa.

    Angular Select Example

    Abaixo está um exemplo básico Angular Select. Ele tem um menu contextual simples que exibe uma lista de várias escolhas abrindo por clique.

    Getting Started with Ignite UI for Angular Select

    Para começar a usar o componente Ignite UI for Angular Select, 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 oIgxSelectModule arquivo no app.module.ts.

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

    Alternativamente,16.0.0 você pode importarIgxSelectComponent como uma dependência independente ou usar oIGX_SELECT_DIRECTIVES token para importar o componente e todos os seus componentes e diretivas de suporte.

    // home.component.ts
    
    import { FormsModule } from '@angular/forms';
    import { IGX_SELECT_DIRECTIVES } from 'igniteui-angular';
    // import { IGX_SELECT_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-select [(ngModel)]="selected">
            <label igxLabel>Simple Select</label>
            <igx-select-item value="Orange">Orange</igx-select-item>
            <igx-select-item value="Apple">Apple</igx-select-item>
            <igx-select-item value="Banana">Banana</igx-select-item>
            <igx-select-item value="Mango">Mango</igx-select-item>
        </igx-select>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_SELECT_DIRECTIVES, FormsModule]
        /* or imports: [IgxSelectComponent, IgxSelectItemComponent, IgxLabelDirective, FormsModule] */
    })
    export class HomeComponent {
        public selected: string;
    }
    

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

    Using the Angular Select

    Add the igx-select along with a list of items to choose from. We use igx-select-item to display the items that the igx-select contains.

    <igx-select>
        <label igxLabel>Simple Select</label>
        <igx-select-item value="Orange">Orange</igx-select-item>
        <igx-select-item value="Apple">Apple</igx-select-item>
        <igx-select-item value="Banana">Banana</igx-select-item>
        <igx-select-item value="Mango">Mango</igx-select-item>
    </igx-select>
    

    Outra maneira de fazer isso seria usar uma coleção de itens que queremos exibir usando a diretiva estrutural *ngFor:

    public items: string[] = ['Orange', 'Apple', 'Banana', 'Mango'];
    
    <igx-select [(ngModel)]="selected">
        <label igxLabel>Simple Select</label>
        <igx-select-item *ngFor="let item of items" [value]="item">
            {{item}}
        </igx-select-item>
    </igx-select>
    

    By default, the Select component will use the innerText of the item element in the input field. In cases with more complex item templates, you can explicitly set the text property to specify what to display in the input field when this item is selected. For example:

    <igx-select>
        <igx-select-item *ngFor="let item of items" [value]="item.value" [text]="item.text">
            {{item.text}} ( {{item.count}} )
        </igx-select-item>
    </igx-select>
    

    To see the text property in action with a bit more sophisticated item templates, check the grouping sample below Select with Groups section.

    Input Properties

    O componente Select suporta as seguintes diretivas aplicáveis ao Grupo de Entrada:

    • igxLabel - No need to set the for property, as linking with the Angular Select input is handled automatically via aria-labelledby.
    • igx-prefix/igxPrefix
    • igx-suffix/igxSuffix - Note the built-in toggle button suffix will always be displayed last.
    • igx-hint/igxHint
    <igx-select [(ngModel)]="selected">
        <label igxLabel>Pick a fruit</label>
        <igx-prefix>
            <span class="bio-prefix">BIO</span>
        </igx-prefix>
        <igx-suffix *ngIf="selected">
            <igx-icon (click)="clearSelection($event)">clear</igx-icon>
        </igx-suffix>
        <igx-hint>Choose a banana</igx-hint>
        <igx-select-item *ngFor="let item of items" [value]="item">
            {{item}}
        </igx-select-item>
    </igx-select>
    

    Note

    If no placeholder is specified for the Select component and there is no selection made, the igxLabel will transition and appear where you would expect the placeholder to be.

    Group Select Items

    To help visually separate item groups, the select component supports item grouping by wrapping items in an <igx-select-item-group>. This works best with hierarchical data that can be iterated to declare the components. In the following example, each group has a label and a collection of items:

    public greengrocery: Array<{ label: string, items: Array<{ type: string, origin: string }> }> = [
        { label: 'Fruits', items: [
                { type: 'Apple', origin: 'local' },
                { type: 'Orange', origin: 'import' },
                { type: 'Banana', origin: 'import'}
            ]
        },
        { label: 'Vegetables', items: [
                { type: 'Cucumber', origin: 'local' },
                { type: 'Potato', origin: 'import' },
                { type: 'Pepper', origin: 'local' }
            ]
        }
    ];
    

    Então, no seu arquivo de modelo, você pode iterar sobre os objetos e acessar seus itens adequadamente:

    <igx-select #select>
        <label igxLabel>Select With Groups</label>
        <igx-select-item-group *ngFor="let group of greengrocery" [label]="group.label">
            <igx-select-item *ngFor="let item of group.items" [value]="item.type" [text]="item.type">
                {{item.type}}
                <igx-icon
                    title="Local product"
                    *ngIf="item.origin === 'local'; else templateImport"
                >local_shipping</igx-icon>
                <ng-template #templateImport>
                    <igx-icon title="Import product">flight</igx-icon>
                </ng-template>
            </igx-select-item>
        </igx-select-item-group>
    </igx-select>
    

    Currently, there are no default header and footer templates for the Select component. However, you can add a header or a footer template by marking them respectively with igxSelectHeader or igxSelectFooter. As these are custom templates, you should define their styling as well. In this example, there are both header and footer ng-templates defined. In the header there is a basic filtering, implemented via igx-buttongroup. The footer includes static summary of all of the items, based on the delivery method.

    <igx-select>
        <label igxLabel>Pick your fruit</label>
        <igx-select-item *ngFor="let fruit of fruits" [value]="fruit.type" [text]="fruit.type" [ngSwitch]="fruit.delivery">
            {{fruit.type}}
            <igx-icon *ngSwitchCase="'flight'">flight</igx-icon>
            <igx-icon *ngSwitchCase="'train'">train</igx-icon>
            <igx-icon *ngSwitchCase="'boat'">directions_boat</igx-icon>
        </igx-select-item>
        <ng-template igxSelectHeader>
            <div class="custom-select-header">
                <span class="sample-template-heading">DELIVERY METHOD</span>
                <igx-buttongroup (click)="filter($event.target.title)">
                        <button igxButton title="flight"><igx-icon title="flight">flight</igx-icon></button>
                        <button igxButton title="train"><igx-icon title="train">train</igx-icon></button>
                        <button igxButton title="boat"><igx-icon title="boat">directions_boat</igx-icon></button>
                </igx-buttongroup>
            </div>
        </ng-template>
        <ng-template igxSelectFooter>
            <div class="custom-select-footer">
                <span class="sample-template-heading">TOTAL</span>
                <div class="sample-template-icons">
                    <span class="sample-template-icons__item">
                        <igx-icon
                            title="flight"
                            [class.important-icon]="selected === 'flight'"
                        >flight</igx-icon>
                        {{flightCount}}
                    </span>
                    <span class="sample-template-icons__item">
                        <igx-icon
                            title="train"
                            [class.important-icon]="selected === 'train'"
                        >train</igx-icon>
                        {{trainCount}}
                    </span>
                    <span class="sample-template-icons__item">
                        <igx-icon
                            title="boat"
                            [class.important-icon]="selected === 'boat'"
                        >directions_boat
                        </igx-icon>
                        {{boatCount}}
                    </span>
                </div>
            </div>
        </ng-template>
    </igx-select>
    

    Custom Toggle Button in Angular Select

    You can customize the default toggle button, using the igxSelectToggleIcon directive or setting a TemplateRef to the toggleIconTemplate property.

    <igx-select #select>
        ...
        <ng-template igxSelectToggleIcon let-collapsed>
            <igx-icon>{{ collapsed ? 'add_circle' : 'add_circle_outline'}}</igx-icon>
        </ng-template>
        ...
    <igx-select>
    

    Keyboard Navigation

    • Open the igx-select by clicking on the Space, Enter or ALT + Up/Down Arrow keys, while the select is focused.
    • Close the igx-select using the ALT + Up/Down Arrow combination or any of the Enter, Space, Esc or Tab keys.
    • Using the Up/Down Arrow keys will navigate through the items.
    • Using the Home or End keys will navigate you to the first and last items in the list.
    • Você pode navegar pelos itens da lista, começando com um determinado caractere, pressionando a tecla correspondente.
    • Você pode navegar até um item específico digitando rapidamente os primeiros caracteres do item que deseja acessar.
    • Select an item using the Enter or Space keys
    Note

    igx-select supports only single selection of items.

    Você também pode experimentar o App Builder ™ de arrastar e soltar para ver como ele automatiza certos processos e reduz a necessidade de codificação manual excessiva ao criar seu próximo aplicativo Angular.

    Custom Overlay Settings

    You can create custom OverlaySettings. To do this you first define your template like so:

    <igx-select [overlaySettings]="customOverlaySettings">
        <igx-select-item *ngFor="let item of items">
            {{item}}
        </igx-select-item>
    </igx-select>
    
    • Where the overlaySettings property is bound to your custom settings.

    Dentro da sua classe, você teria algo como:

    export class MyClass implements OnInit {
        @ViewChild(IgxSelectComponent)
        public select: IgxSelectComponent;
        public items: string[] = ['Orange', 'Apple', 'Banana', 'Mango', 'Tomato'];
        public customOverlaySettings: OverlaySettings;
    
        public ngOnInit(): void {
            const positionSettings: PositionSettings = {
                closeAnimation: scaleOutBottom,
                horizontalDirection: HorizontalAlignment.Right,
                horizontalStartPoint: HorizontalAlignment.Left,
                openAnimation: scaleInTop,
                verticalDirection: VerticalAlignment.Bottom,
                verticalStartPoint: VerticalAlignment.Bottom
            };
            this.customOverlaySettings = {
                target: this.select.inputGroup.element.nativeElement,
                positionStrategy: new ConnectedPositioningStrategy(
                    positionSettings
                ),
                scrollStrategy: new AbsoluteScrollStrategy()
            };
        }
    }
    

    Você pode ver que criamos um objeto PositionSettings que é passado diretamente para nossa ConnectedPositioningStrategy, não é obrigatório fazer isso, mas como queremos definir um posicionamento personalizado, os usamos para substituir as configurações padrão da estratégia.

    • Você pode definir todas as configurações dentro do gancho ngOnInit e isso afetará automaticamente seu modelo na geração do componente.

    Você também pode passar um objeto OverlaySettings personalizado para a função open do IgxSelectComponent, onde seu modelo deve ficar assim:

    <igx-select>
        <igx-select-item *ngFor="let item of items">
            {{item}}
        </igx-select-item>
    </igx-select>
    
    <button (click)="onClick($event)"></button>
    

    E sua classe tem o seguinte:

    export class MyClass implements OnInit {
        /* -- */
        private otherCustomOverlaySettings: OverlaySettings = {
            positionStrategy: new GlobalPositionStrategy(),
            scrollStrategy: new AbsoluteScrollStrategy()
        }
        onClick(event: MouseEvent): void {
            this.select.open(this.otherCustomOverlaySettings)
        }
        /* -- */
    }
    
    Note

    If you pass in your custom settings both as an argument in the open function and in the template, igx-select will use the one provided in the open function. However, if you bind the settings to an internal event, such as opening or opened then igx-select will use the settings that are provided in the template.

    Estilização

    Select Theme Property Map

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

    Propriedade primária Propriedade dependente Descrição
    $toggle-botão de fundo
    $toggle-botão em primeiro plano Cor em primeiro plano do botão de alternar
    $toggle-botão cheio de primeiro planoCor em primeiro plano quando o botão de alternar é preenchido
    $toggle-botão-fundo-focoCor de fundo quando focado
    $toggle-botão-fundo-foco--borda (bootstrap/índigo)Contexto quando focado na variante de borda (Bootstrap/Indigo)
    $toggle-botão de foco em primeiro planoCor em primeiro plano quando o botão de alternar está focado

    Cada componente tem sua própria função temática.

    To get the Select component styled, you have to style its containing components. In our case, these are the input-group-theme and the drop-down-theme. Take a look at the Input Group and the Drop Down styling sections to get a better understanding of how to style those two components.

    We also have a select-theme function which is used only for styling the button of our Select component.
    To get started with styling the Select component button, 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 select-theme and provide only the $toggle-button-background parameter. The theme function will automatically calculate all corresponding background and foreground colors for the different states based on this single value.

    $custom-select-theme: select-theme(
      $toggle-button-background: #57a5cd,
    );
    

    O último passo é passar o tema de rádio personalizado em nossa aplicação:

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

    Styling with Tailwind

    Você pode estilizar a seleção usando nossas classes utilitárias personalizadas do 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-select,dark-select.

    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 seletivo. A sintaxe é a seguinte:

    <igx-select
      class="!light-select ![--toggle-button-background:#99BAA6]">
      ...
    </igx-select>
    
    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, sua seleção deve ficar assim:

    API Reference

    Theming Dependencies

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.