Descripción general Blazor ComboBox

    Blazor ComboBox es un editor liviano que permite a los usuarios seleccionar, filtrar y agrupar fácilmente diferentes opciones predefinidas en una lista proporcionada. El componente también admite opciones para la navegación con el teclado Blazor ComboBox, plantillas para personalizar cómo se muestran los elementos, el encabezado y el pie de página.

    El componente ComboBox Ignite UI for Blazor ofrece una lista de opciones entre las que los usuarios pueden elegir. Muestra todas las opciones en una lista virtualizada de elementos, lo que significa que el ComboBox puede mostrar simultáneamente miles de registros, en los que se pueden seleccionar una o más opciones. Además, el componente cuenta con funciones de filtrado que distinguen entre mayúsculas y minúsculas, agrupación, vinculación de datos complejos y más.

    Blazor ComboBox Example

    Getting Started with Blazor ComboBox

    To get started with the IgbCombo component, first we need to register its module as follows:

    // in Program.cs file
    
    builder.Services.AddIgniteUIBlazor(typeof(IgbComboModule));
    

    You will also need to link an additional CSS file to apply the styling to the IgbCombo component. The following needs to be placed in the wwwroot/index.html file in a Blazor Web Assembly project or the Pages/_Host.cshtml file in a Blazor Server project:

    <link href="_content/IgniteUI.Blazor/themes/light/bootstrap.css" rel="stylesheet" />
    

    [!WARNING] The IgbCombo component doesn't work with the standard <form> element. Use Form instead.

    Luego, vincularemos una serie de objetos a la fuente de datos combinada utilizada para crear la lista de opciones.

    <IgbCombo T="object" Id="basic-combo" DisplayKey="name" ValueKey="id" Data="Data" />
    
    @code {
        private class City {
            public string Id { get; set; }
            public string Name { get; set; }
            public string Country { get; set; }
        }
    
        private List<City> Data = new List<City> {
            new City {
                Id = "UK01",
                Name = "London",
                Country = "United Kingdom",
            },
            new City {
                Id = "BG01",
                Name = "Sofia",
                Country = "Bulgaria",
            },
            new City {
                Id = "US01",
                Name = "New York",
                Country = "United States",
            },
        };
    }
    

    Data value and display properties

    Cuando el combo está vinculado a una lista de datos complejos (es decir, objetos), necesitamos especificar una propiedad que el control utilizará para manejar la selección de elementos. El componente expone las siguientes propiedades:

    • T - required, if ValueKey is omitted, this should be set to "object", otherwise this needs to match the property type of ValueKey.
    • ValueKey - Optional, required for complex data object - Determines which field of the data source will be used to make selections. If ValueKey is omitted, the selection API will use object references to select items.
    • DisplayKey - Optional, recommended for complex data objects - Determines which field in the data source is used as the display value. If no value is specified for DisplayKey, the combo will use the specified ValueKey (if any). In our case, we want the combo to display the name of each city and use the id field for item selection and as the underlying value for each item. Therefore, we provide these properties to the combo's ValueKey and DisplayKey respectively.

    [!Note] When the data source consists of primitive types (e.g. strings, numbers, etc.), do not specify a ValueKey and/or DisplayKey.

    Setting Value

    The ComboBox component exposes a Value getter and setter in addition to an attribute, which is also called value. You can use the value attribute to set the selected items on component initialization.

    If you want to read the value, i.e. the list of currently selected items, or to update the value use the value getter and setter respectively. The value getter will return a list of all selected items as represented by the ValueKey. Likewise, if you want to update the list of selected items by using the value setter, you should provide a list of items by their ValueKey.

    Ejemplo:

    Selection API

    El componente combinado expone API que le permiten cambiar los elementos seleccionados actualmente.

    Besides selecting items from the list of options by user interaction, you can select items programmatically. This is done via the Select and Deselect methods. You can pass an array of items to both methods. If the methods are called with no arguments all items will be selected/deselected depending on which method is called. If you have specified a ValueKey for your combo component, then you should pass the value keys of the items you would like to select/deselect:

    Seleccionar/deseleccionar algunos elementos

    <IgbCombo
        @ref="Combo"
        Label="Cities"
        Placeholder="Pick a city"
        Data="Data"
        ValueKey="Id"
        DisplayKey="Name">
    </IgbCombo>
    
    @code {
        private List<City> Data;
        private IgbCombo Combo;
        private object[] Cities;
    
        protected override void OnInitialized() {
            this.Data = SampleData.Cities;
            this.Cities = new object[] { "UK01", "UK02", "UK03", "UK04", "UK05" };
        }
    
        public void SelectCities() {
            this.Combo.Select(Cities);
        }
    
        public void DeselectCities() {
            this.Combo.Deselect(Cities);
        }
    }
    

    Seleccionar/deseleccionar todos los elementos

    @code {
        public void SelectAll() {
            this.Combo.Select(new object[] {});
        }
    
        public void DeselectAll() {
            this.Combo.Deselect(new object[] {});
        }
    }
    

    If the ValueKey property is omitted, you will have to list the items you wish to select/deselect as objects references:

    Validation

    The Ignite UI for Blazor Combo component supports most of the IgbInput properties, such as Required, Disabled, Autofocus, Invalid, etc. The component also exposes two methods bound to its validation:

    • ReportValidity - checks for validity and returns true if the component satisfies the validation constraints.
    • CheckValidity - a wrapper around reportValidity to comply with the native input API.

    Keyboard Navigation

    Cuando el componente combinado está enfocado y la lista de opciones no está visible:

    • Abra la lista de opciones usando las teclas Abajo/Alt + Abajo.

    Cuando el componente combinado está enfocado y la lista de opciones está visible:

    • Usar la tecla Abajo activará el siguiente elemento de la lista.
    • Usar la tecla Arriba activará el elemento anterior de la lista. Si el primer elemento ya está activo, centrará la entrada.
    • El uso de las HOME teclas o END activará el primer o el último elemento de la lista.
    • Usando la SPACE clave se seleccionará el elemento activo.
    • Al usar la ENTER clave, se seleccionará el elemento activo y se cerrará la lista de opciones.
    • El uso de las ESC teclas o TAB/SHIFT + TAB, se cerrará la lista de opciones.

    Styling

    You can change the appearance of the IgbCombo component and its items, by using the exposed CSS parts listed below:

    Nombre de la pieza Descripción
    label La etiqueta de texto encapsulado.
    input El campo de entrada principal.
    native-input La entrada nativa del campo de entrada principal.
    prefix El contenedor de prefijo.
    suffix El contenedor del sufijo.
    toggle-icon El contenedor del icono de alternancia.
    clear-icon El contenedor de iconos claros.
    case-icon Un contenedor de ícono de caso que presenta contenido dentro del sufijo de la entrada del filtro.
    helper-text El contenedor de texto auxiliar.
    search-input El campo de entrada de búsqueda.
    list-wrapper La lista de opciones de contenedor.
    list El cuadro de lista de opciones.
    item Representa cada elemento de la lista de opciones.
    group-header Representa cada encabezado en la lista de opciones.
    active Se agrega a la lista de piezas del artículo cuando el artículo está activo.
    selected Se adjunta a la lista de piezas del artículo cuando se selecciona el artículo.
    checkbox Representa cada casilla de verificación de cada elemento de la lista.
    checkbox-indicator Representa el indicador de casilla de verificación de cada elemento de la lista.
    checked Se adjunta a la lista de piezas de la casilla de verificación cuando la casilla de verificación está marcada.
    header El contenedor que contiene el contenido del encabezado.
    footer El contenedor que contiene el contenido del pie de página.
    empty El contenedor que contiene el contenido vacío.

    Usando las partes CSS, tenemos control total sobre el estilo Combo.

    igc-combo::part(search-input) {
      background-color: var(--ig-gray-100);
      border-radius: 2px;
    }
    
    igc-combo::part(input) {
      background-color: var(--ig-gray-100);
    }
    
    igc-combo::part(prefix) {
      background-color: var(--ig-secondary-50);
      color: var(--ig-primary-500);
    }
    
    igc-combo::part(toggle-icon) {
      color: var(--ig-primary-500);
    }
    

    API Reference

    Additional Resources