Descripción general del componente ComboBox Angular
El componente ComboBox Angular representa una lista desplegable que proporciona funcionalidades editables, lo que permite a los usuarios elegir varias opciones de una lista predefinida. El componente ComboBox Ignite UI for Angular también proporciona capacidades de filtrado, agrupación y adición de valores personalizados a una lista desplegable. Se puede usar como alternativa a la etiqueta de selección HTML y tiene varias características listas para usar, como enlace de datos (local y remoto), filtrado, agrupación, plantillas personalizadas para elementos, encabezado y pie de página, valores personalizados y más.
Angular ComboBox Example
En este ejemplo de ComboBox Angular, puede ver cómo los usuarios pueden filtrar elementos y realizar selecciones con los datos proporcionados. Además, ComboBox muestra navegación mediante teclado y capacidades de estilo personalizado.
Angular ComboBox Features
El control de cuadro combinado expone las siguientes características:
- Enlace de datos: datos locales y datos remotos
- Enlace de valor
- Filtración
- Agrupamiento
- Valores personalizados
- Plantillas
- Integración con formularios basados en plantillas y formularios reactivos
Getting Started with Ignite UI for Angular ComboBox
Para comenzar con el componente Ignite UI for Angular ComboBox, 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.
El siguiente paso es importarlosIgxComboModule en tu archivo app.module.ts.
import { IgxComboModule } from 'igniteui-angular/combo';
// import { IgxComboModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
imports: [
...
IgxComboModule,
...
]
})
export class AppModule {}
Alternativamente,16.0.0 puedes importarlosIgxComboComponent como una dependencia independiente, o usar elIGX_COMBO_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.
// home.component.ts
import { IGX_COMBO_DIRECTIVES } from 'igniteui-angular/combo';
// import { IGX_COMBO_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: '<igx-combo></igx-combo>',
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IGX_COMBO_DIRECTIVES]
/* or imports: [IgxComboComponent] */
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Combo module or directives imported, you can start using the igx-combo component.
Using the Angular ComboBox Component
Después de la configuración inicial, puede vincular el igx-combo a los datos.
@Component({
selector: 'app-combo-demo',
template: '<igx-combo [data]="cities"></igx-combo>',
styleUrls: ['combo-demo.component.scss'],
standalone: true,
imports: [IGX_COMBO_DIRECTIVES]
})
export class ComboDemo implements OnInit {
public cities: { name: string, id: string }[] = [];
public ngOnInit() {
this.cities = [{ name: 'London', id: 'UK01' }, { name: 'Sofia', id: 'BG01'}, ...];
}
}
Nuestro cuadro combinado ahora está vinculado al conjunto de ciudades, pero todavía no le hemos dicho al componente qué propiedad usar para el texto de los elementos y cuál usar para el valor. Hagámoslo ahora.
Data value and display properties
Since the combobox is bound to an array of complex data (i.e. objects), we need to specify a property that the control will use to handle the selected items. The control exposes two @Input properties - valueKey and displayKey:
valueKey- Optional, recommended for object arrays - Specifies which property of the data entries will be stored for the combobox's selection. IfvalueKeyis omitted, the combobox value will use references to the data entries (i.e. the selection will be an array of entries fromigxCombo.data).displayKey- Required for object arrays - Specifies which property will be used for the items' text. If no value is specified fordisplayKey, the combobox will use the specifiedvalueKey(if any).
In our case, we want the combobox to display the name of each city and the combobox value to store the id of each city. Therefore, we are providing these properties to the combobox's displayKey and valueKey, respectively:
<igx-combo [data]="cities" displayKey="name" valueKey="id"></igx-combo>
Note
When the data source is an array of primitives (e.g. string[], number[]), do not specify a valueKey and displayKey. Primitive values will be used for both value and text.
Encuadernación bidireccional
The combobox component fully supports two-way data-binding with [(ngModel)] as well as usage in template driven and reactive forms. The combobox selection can be accessed either through two-way binding or through the selection API. We can pass an array of items of the same type as the ones in the combobox's selection (based on valueKey) and any time one changes, the other is updated accordingly.
In the following example, the cities Sofia and London will initially be selected. Any further changes in the combobox's selection will reflect on the selectedCities array.
<igx-combo [data]="cities" [(ngModel)]="selectedCities" displayKey="name" valueKey="id"></igx-combo>
export class MyCombo {
public cities: { name: string, id: string }[] = [
{ name: 'Sofia', id: 'BG01' }, { name: 'London', id: 'UK01' }, ...];
public selectedCities: string[] = ['BG01', 'UK01'];
}
Two-way binding can also be achieved without a specified valueKey. For example, if valueKey is omitted, the bound model will look like this:
export class MyCombo {
public cities: { name: string, id: string } [] = [
{ name: 'Sofia', id: 'BG01' }, { name: 'London', id: 'UK01' }, ...];
public selectedCities: { name: string, id: string } [] = [this.cities[0], this.cities[1]];
}
Selection API
El componente del cuadro combinado expone una API que permite obtener y manipular el estado de selección actual del control.
Una forma de obtener la selección del cuadro combinado es mediante la propiedad de selección. Devuelve una matriz de valores que corresponden a los elementos seleccionados, según la clave de valor especificada (si corresponde).
In our example, selection will return an array of the selected cities' ids:
export class MyCombo {
...
public selection: string[] = this.combo.selection;
}
Usando la API de selección, también puede cambiar los elementos seleccionados del cuadro combinado sin interacción del usuario con el control, mediante un clic en un botón, como respuesta a un cambio Observable, etc. Por ejemplo, podemos implementar un botón que seleccione un conjunto de ciudades, usando el método select():
<igx-combo [data]="cities" displayKey="name" valueKey="id"></igx-combo>
<button igxButton (click)="selectFavorites()">Select Favorites</button>
Al hacer clic en el botón, las ciudades Londres y Sofía se agregarán a la selección del cuadro combinado:
export class MyExampleCombo {
@ViewChild(IgxComboComponent, { read: IgxComboComponent, static: true })
public combo: IgxComboComponent;
...
selectFavorites(): void {
this.combo.select(['UK01', 'BG01']);
}
}
El cuadro combinado también activa un evento cada vez que cambia su selección: selecciónChanging(). Los argumentos del evento emitido, IComboSelectionChangingEventArgs, contienen información sobre la selección anterior al cambio, la selección actual y los elementos que se agregaron o eliminaron. El evento también se puede cancelar, impidiendo la actualización de la selección con la nueva matriz de elementos.
Binding to the event can be done through the proper @Output property on the igx-combo tag:
<igx-combo [data]="cities" displayKey="name" valueKey="id"
(selectionChanging)="handleCityChange($event)">
</igx-combo>
En el siguiente ejemplo, cuando se agrega o elimina una ciudad de la selección, se activa un controlador que actualiza la visualización de estadísticas:
export class MyExampleCombo {
...
handleCityChange(event: IComboSelectionChangeEventArgs): void {
for (const item of event.added) {
this.addToVisualization(item);
}
for (const item of event.removed) {
this.removeFromVisualization(item);
}
}
}
Single Selection
By default, the combo control provides multiple selection. The snippet below demonstrates how to achieve single selection in the component by attaching a handler to the selectionChanging event:
<igx-combo [data]="lData" (selectionChanging)="singleSelection($event)"></igx-combo>
public singleSelection(event: IComboSelectionChangeEventArgs) {
if (event.added.length) {
event.newValue = event.added;
}
}
Nota: Se recomienda utilizar igxSimpleCombo en lugar de modificar igxCombo como se muestra arriba.
Keyboard Navigation
Cuando el cuadro combinado está cerrado y enfocado:
ArrowDownorAlt+ArrowDownwill open the combobox's drop down and will move focus to the search input.
Cuando se abre el cuadro combinado y la entrada de búsqueda está enfocada:
ArrowUporAlt+ArrowUpwill close the combobox's drop down and will move focus to the closed combobox.ArrowDownwill move focus from the search input to the first list item. If the list is empty and custom values are enabled will move it to the Add new item button.
Note
Cualquier otra pulsación de tecla será manejada por la entrada.
Cuando se abre el cuadro combinado y el elemento de la lista está enfocado:
ArrowDownwill move to the next list item. If the active item is the last one in the list and custom values are enabled, the focus will be moved to the Add item button.ArrowUpwill move to the previous list item. If the active item is the first one in the list, the focus will be moved back to the search input.Endwill move to the last list item.Homewill move to the first list item.Spacewill select/deselect the active list item.Enterwill confirm the already selected items and will close the list.Escwill close the list.
Cuando se abre el cuadro combinado, se habilitan los valores personalizados y el botón Agregar elemento está enfocado:
Enterwill add a new item withvalueKeyanddisplayKeyequal to the text in the search input and will select the new item.ArrowUpfocus will be moved back to the last list item or if the list is empty, will be moved to the search input.
Estilismo
Combo Theme Property Map
Cuando modificas una propiedad primaria, todas las propiedades dependientes relacionadas se actualizan automáticamente:
| Propiedad principal | Propiedad dependiente | Descripción |
|---|---|---|
| $empty-lista de antecedentes | $empty-lista-placeholder-color | El color de texto provisional combinado. |
$toggle-fondo de botones |
$toggle-botón en primer plano | El botón de combo activa el color del primer plano. |
| $toggle-botón-fondo-enfoque | El botón de combo activa el color de fondo cuando está enfocado. | |
| $toggle-botón-fondo-enfoque--borde | El botón de interruptor activa el color de fondo cuando se enfoca (variante de borde). | |
| $toggle-lleno de botones en primer plano | El botón de interruptor de combo cambia el color del primer plano cuando está lleno. | |
| $toggle-botón-fondo-desactivado | El botón combo activa el color de fondo cuando está desactivado. | |
| $toggle-botón-primer plano-desactivado | El botón de combo activa el color del primer plano cuando está desactivado. | |
| $toggle-botón-fondo-enfoque | $toggle-botón-primer plano-enfoque | El botón de interruptor de combo activa el color del primer plano cuando está enfocado. |
| $clear-botón-fondo-enfoque | $clear-botón-primer plano | El botón de combo para limpiar el color del primer plano cuando está enfocado. |
Using the Ignite UI for Angular Theming, we can greatly alter the combobox appearance. First, in order for us to use the functions exposed by the theme engine, we need to import the index file in our style file:
@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 combo-theme. By setting the $toggle-button-background, the theme automatically determines suitable state colors and contrast foregrounds for the button. You can also specify additional parameters, such as $search-separator-border-color:
$custom-combo-theme: combo-theme(
$search-separator-border-color: #1d3743,
$toggle-button-background: #57a5cd,
);
The IgxComboComponent uses the IgxDropDownComponent internally as an item container. It also includes the IgxInputGroup and the IgxCheckbox components. Creating new themes, that extend these components' themes, and scoping them under the respective classes will let you change the combobox styles:
$custom-drop-down-theme: drop-down-theme(
$background-color: #57a5cd,
);
$custom-checkbox-theme: checkbox-theme(
$border-radius: 10px,
$fill-color: #1d3743,
$empty-color: #1d3743,
);
El último paso es incluir el tema del componente.
:host ::ng-deep {
@include css-vars($custom-combo-theme);
@include css-vars($custom-drop-down-theme);
@include css-vars($custom-checkbox-theme);
}
Note
The IgxCombo component uses the IgxOverlay service to hold and display the combobox items list container. To properly scope your styles you might have to use an OverlaySetting.outlet. For more details check the IgxOverlay Styling Guide. Also is necessary to use ::ng-deep when we are styling the components.
Note
The default type of the IgxCombo is box unlike the IgxSelect where it is line.
Demo
Styling with Tailwind
Puedes decorarloscombo 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';
El archivo de utilidad incluye variantes tantolight comodark de tema.
- Usa
light-*clases para el tema ligero. - Usa
dark-*clases para el tema oscuro. - Añadir el nombre del componente después del prefijo, por ejemplo, ,
light-combo,dark-combo.
Una vez aplicadas, estas clases permiten cálculos dinámicos de temas. Desde ahí, puedes anular las variables CSS generadas usandoarbitrary properties. Después de los dos puntos, proporciona cualquier formato de color CSS válido (HEX, variable CSS, RGB, etc.).
Puedes encontrar la lista completa de propiedades en el tema combinado. La sintaxis es la siguiente:
<igx-combo
class="!light-combo
![--toggle-button-background:#99BAA6]
![--clear-button-foreground:#99BAA6]"
...></igx-combo>
Note
El signo de exclamación(!) es necesario para asegurar que la clase de utilidad tenga prioridad. Tailwind aplica estilos en capas y, sin marcar estos estilos como importantes, serán anulados por el tema predeterminado del componente.
Al final tu combo debería verse así:
Known Issues
- La entrada del cuadro combinado que muestra los elementos seleccionados no es editable. Sin embargo, debido a las características específicas del navegador Firefox, el cursor está visible.
- When the combobox is bound to an array of primitive data which contains
undefined(i.e.[ undefined, ...]),undefinedis not displayed in the dropdown. When it is bound to an array of complex data (i.e. objects) and the value used forvalueKeyisundefined, the item will be displayed in the dropdown, but cannot be selected. - Cuando el combobox está vinculado a un servicio remoto y hay una selección predefinida, su entrada permanecerá en blanco hasta que se carguen los datos solicitados.
Note
The combobox uses igxForOf directive internally hence all igxForOf limitations are valid for the combobox. For more details see igxForOf Known Issues section.
API Summary
Componentes angulares adicionales y/o directivas con API relativas que se utilizaron:
Theming Dependencies
Additional Resources
- Funciones del cuadro combinado
- Enlace remoto de ComboBox
- Plantillas de cuadros combinados
- Integración de formularios basados en plantillas
- Integración de formularios reactivos
- Cuadro combinado de selección única
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.