Descripción general del componente de selección Angular

    Angular Select es un componente de formulario que se utiliza para seleccionar un único valor de una lista de valores predefinidos. El componente Angular Select proporciona una funcionalidad idéntica a la del elemento de selección HTML nativo, pero ofrece muchas más opciones de personalización. Se basa en IgxDropDownComponent y admite todas sus funciones, incluidas las plantillas, la virtualización y la personalización de los elementos de la lista desplegable.

    Angular Select Example

    A continuación se muestra un ejemplo básico de selección Angular. Tiene un menú contextual simple que muestra una lista de varias opciones que se abren con cada clic.

    Getting Started with Ignite UI for Angular Select

    Para comenzar con el componente Ignite UI for Angular Select, 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.

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

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

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

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

    Otra forma de hacerlo sería utilizar una colección de elementos que queremos mostrar usando la directiva estructural *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

    El componente Seleccionar admite las siguientes directivas aplicables al 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' }
            ]
        }
    ];
    

    Luego, en su archivo de plantilla puede iterar sobre los objetos y acceder a sus elementos en consecuencia:

    <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.
    • Puede navegar por los elementos de la lista, comenzando con un determinado carácter, presionando la tecla correspondiente.
    • Puede navegar a un elemento específico escribiendo rápidamente los primeros caracteres del elemento al que desea ir.
    • Select an item using the Enter or Space keys
    Note

    igx-select supports only single selection of items.

    También puede probar el App Builder ™de arrastrar y soltar para ver cómo automatiza ciertos procesos y reduce la necesidad de una codificación manual excesiva al crear su próxima aplicación 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 de tu clase, tendrías 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()
            };
        }
    }
    

    Puede ver que creamos un objeto PositionSettings que se pasa directamente a nuestra ConnectedPositioningStrategy, no es necesario hacerlo, pero como queremos definir un posicionamiento personalizado, los usamos para anular la configuración predeterminada de la estrategia.

    • Puede establecer todas las configuraciones dentro del gancho ngOnInit y esto afectará automáticamente su plantilla tras la generación del componente.

    También puede pasar un objeto OverlaySettings personalizado a la función abierta de IgxSelectComponent, donde su plantilla debería verse así:

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

    Y tu clase tiene lo siguiente:

    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.

    Estilismo

    Select Theme Property Map

    Al modificar una propiedad principal, todas las propiedades dependientes relacionadas se actualizan automáticamente para reflejar el cambio:

    Propiedad principal Propiedad dependiente Descripción
    $toggle-fondo de botones
    $toggle-botón en primer plano Color en primer plano del botón de alternancia
    $toggle-lleno de botones en primer planoColor del primer plano cuando se llena el botón de interruptor
    $toggle-botón-fondo-enfoqueColor de fondo cuando se enfoca
    $toggle-botón-fondo-enfoque--borde (bootstrap/índigo)Fondo cuando se enfoca en la variante de borde (Bootstrap/Índigo)
    $toggle-botón-primer plano-enfoqueColor del primer plano cuando el botón de alternancia está enfocado

    Cada componente tiene su propia función de tema.

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

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

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

    Styling with Tailwind

    Puedes estilizar la selección 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';
    

    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-select, dark-select.

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

    Puedes encontrar la lista completa de propiedades en el select-theme. La sintaxis es la siguiente:

    <igx-select
      class="!light-select ![--toggle-button-background:#99BAA6]">
      ...
    </igx-select>
    
    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.

    Al final, tu selección debería verse así:

    API Reference

    Theming Dependencies

    Additional Resources

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