Descripción general del componente ComboBox de selección única Angular
El componente ComboBox de selección única Angular es una modificación del componente ComboBox que permite una selección única. Lo llamamos "combo simple". Debido a la alta demanda del modo de selección única para el componente ComboBox original, creamos un componente de extensión que ofrece una entrada de búsqueda editable que permite a los usuarios elegir una opción de una lista predefinida de elementos e ingresar valores personalizados.
Angular Simple ComboBox Example
En este ejemplo de cuadro combinado simple Angular, puede ver cómo los usuarios pueden seleccionar el tipo de línea de tendencia del gráfico. Además, el cuadro combinado simple muestra la navegación mediante teclado y las capacidades de estilo personalizado.
Angular Simple ComboBox Features
El control de cuadro combinado simple expone las siguientes características: - Enlace de datos - datos locales y datos remotos - Enlace de valores - Filtrado - Agrupación - Valores personalizados - Plantillas - Integración con formularios basados en plantillas y formularios reactivos
Getting Started with Ignite UI for Angular Simple ComboBox
Para comenzar con el componente Ignite UI for Angular Simple 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.
The next step is to import the IgxSimpleComboModule in your app.module.ts file.
import { IgxSimpleComboModule } from 'igniteui-angular/simple-combo';
// import { IgxSimpleComboModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
imports: [
...
IgxSimpleComboModule,
...
]
})
export class AppModule {}
Alternatively, as of 16.0.0 you can import the IgxSimpleComboComponent as a standalone dependency, or use the IGX_SIMPLE_COMBO_DIRECTIVES token to import the component and all of its supporting components and directives.
// home.component.ts
import { IGX_SIMPLE_COMBO_DIRECTIVES } from 'igniteui-angular/simple-combo';
// import { IGX_SIMPLE_COMBO_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: '<igx-simple-combo></igx-simple-combo>',
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IGX_SIMPLE_COMBO_DIRECTIVES]
/* or imports: [IgxSimpleComboComponent] */
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Simple ComboBox module or directives imported, you can start using the igx-simple-combo component.
Using the Angular Simple ComboBox
Al igual que el cuadro combinado normal, puede vincular el combo igx-simple a los datos.
export class MySimpleComboComponent implements OnInit {
public cities: City[];
public ngOnInit() {
this.cities = getCitiesByPopulation(10000000);
}
}
<igx-simple-combo [data]="cities"></igx-simple-combo>
Nuestro cuadro combinado simple ahora está vinculado a la variedad de ciudades.
Data value and display properties
Since the simple 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 simple combobox's selection. IfvalueKeyis omitted, the simple combobox value will use references to the data entries (i.e. the selection will be an array of entries fromigxSimpleCombo.data).displayKey- Required for object arrays - Specifies which property will be used for the items' text. If no value is specified fordisplayKey, the simple combobox will use the specifiedvalueKey(if any).
In our case, we want the simple combobox to display the name of each city and its value to store the id of each city. Therefore, we are binding these properties as values to the simple combobox's displayKey and valueKey, respectively:
<igx-simple-combo [data]="cities" [displayKey]="'name'" [valueKey]="'id'"></igx-simple-combo>
Note
When the data source is comprised of a simple type (e.g. string[], number[]), do not specify a valueKey and displayKey.
Encuadernación bidireccional
The simple combobox component fully supports two-way data-binding with [(ngModel)] as well as usage in template driven and reactive forms. The simple combobox selection can be accessed either through two-way binding or through the selection API. We can pass in an item of the same type as the ones in the simple combobox's selection (based on valueKey) and any time one changes, the other is updated accordingly.
In the following example, the first city in the provided data will initially be selected. Any further changes in the simple combobox's selection will reflect on the selectedCities.
<igx-simple-combo [data]="cities" [(ngModel)]="selectedCity" [displayKey]="'name'" [valueKey]="'id'"></igx-simple-combo>
export class MySimpleComboComponent implements OnInit {
public cities: City[];
public selectedCity: number;
public ngOnInit(): void {
this.cities = getCitiesByPopulation(10000000);
this.selectedCity = this.cities[0].id;
}
}
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 MySimpleComboComponent {
public cities: City[] = [
{ name: 'Sofia', id: '1' }, { name: 'London', id: '2' }, ...];
public selectedCity: City = this.cities[0];
}
Selection API
El componente de cuadro combinado simple expone una API que permite obtener y manipular el estado de selección actual del control.
Una forma de obtener su selección es mediante la propiedad de selección. Devuelve un valor que corresponde al elemento seleccionado, según la clave de valor especificada (si corresponde).
In our example, selection will return the selected city's id:
export class MySimpleComboComponent {
...
public selection: string = this.simpleCombo.selection;
}
Usando la API de selección, también puede cambiar el elemento seleccionado del cuadro combinado simple 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 selecciona una ciudad, usando el método de selección:
<igx-simple-combo [data]="cities" [displayKey]="'name'" [valueKey]="'id'"></igx-simple-combo>
<button igxButton (click)="selectFavorite()">Select Favorite</button>
When the button is clicked, London will be added to the simple combobox's selection:
export class MySimpleComboComponent {
@ViewChild(IgxSimpleComboComponent, { read: IgxSimpleComboComponent, static: true })
public simpleCombo: IgxSimpleComboComponent;
...
selectFavorites(): void {
this.simpleCombo.select('2');
}
}
El cuadro combinado simple también activa un evento cada vez que cambia su selección: selecciónChanging. Los argumentos del evento emitido, ISimpleComboSelectionChangingEventArgs, contienen información sobre la selección anterior al cambio, la selección actual y el elemento mostrado. El evento también se puede cancelar, impidiendo que se realice la selección.
Binding to the event can be done through the proper @Output property on the igx-simple-combo tag:
<igx-simple-combo [data]="cities" [displayKey]="'name'" [valueKey]="'id'"
(selectionChanging)="handleCityChange($event)">
</igx-simple-combo>
Keyboard Navigation
Cuando el cuadro combinado simple está cerrado y enfocado:
ArrowDownorAlt+ArrowDownwill open the simple combobox's dropdown.
Note
Cualquier otra pulsación de tecla será manejada por la entrada.
Cuando se abre el cuadro combinado simple y se enfoca un elemento de la lista:
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 while also selecting all of the text in the input.Endwill move to the last list item.Homewill move to the first list item.Spacewill select/deselect the active list item.Enterwill select/deselect the active list item and will close the list.Escwill close the list.
Cuando se abre el cuadro combinado simple y 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.ArrowUpwill move the focus back to the last list item or if the list is empty, will move the focus to the input.
Cascading Scenario
El siguiente ejemplo demuestra un escenario en el que se utiliza el combo igx-simple:
Echa un vistazo a nuestro ejemplo de cuadrícula Angular con combos en cascada.
Template Configuration
La API del cuadro combinado simple se utiliza para obtener el elemento seleccionado de un componente y cargar la fuente de datos para el siguiente, así como borrar la selección y la fuente de datos cuando sea necesario.
<igx-simple-combo #country
[data]="countriesData"
(selectionChanging)="countryChanging($event)"
placeholder="Choose Country..."
[(ngModel)]="selectedCountry"
[displayKey]="'name'">
</igx-simple-combo>
<igx-simple-combo #region
[data]="regionData"
(selectionChanging)="regionChanging($event)"
placeholder="Choose Region..."
[(ngModel)]="selectedRegion"
[displayKey]="'name'"
[disabled]="regionData.length === 0">
</igx-simple-combo>
<igx-simple-combo #city
[data]="citiesData"
placeholder="Choose City..."
[(ngModel)]="selectedCity"
[displayKey]="'name'"
[disabled]="citiesData.length === 0">
</igx-simple-combo>
Component Definition
export class SimpleComboCascadingComponent implements OnInit {
public selectedCountry: Country;
public selectedRegion: Region;
public selectedCity: City;
public countriesData: Country[];
public regionData: Region[] = [];
public citiesData: City[] = [];
public ngOnInit(): void {
this.countriesData = getCountries(['United States', 'Japan', 'United Kingdom']);
}
public countryChanging(e: ISimpleComboSelectionChangingEventArgs) {
this.selectedCountry = e.newSelection as Country;
this.regionData = getCitiesByCountry([this.selectedCountry?.name])
.map(c => ({name: c.region, country: c.country}))
.filter((v, i, a) => a.findIndex(r => r.name === v.name) === i);
this.selectedRegion = null;
this.selectedCity = null;
this.citiesData = [];
}
public regionChanging(e: ISimpleComboSelectionChangingEventArgs) {
this.selectedRegion = e.newSelection as Region;
this.citiesData = getCitiesByCountry([this.selectedCountry?.name])
.filter(c => c.region === this.selectedRegion?.name);
this.selectedCity = null;
}
}
Angular Simple ComboBox Remote Binding
El componente ComboBox simple de Ignite UI for Angular expone una API que permite vincular un cuadro combinado a un servicio remoto y recuperar datos a petición.
Demo
El siguiente ejemplo demuestra el enlace remoto utilizando la propiedad dataPreLoad para cargar una nueva porción de datos remotos y siguiendo los pasos descritos en ComboBox Remote Binding:
Estilismo
Using the Ignite UI for Angular Theming, we can greatly alter the simple 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 and accepts the $empty-list-background parameter:
$custom-simple-combo-theme: combo-theme(
$empty-list-background: #1a5214
);
The IgxSimpleComboComponent uses the IgxDropDownComponent internally as an item container. It also includes the IgxInputGroup component. Creating new themes, that extend these components' themes, and scoping them under the respective classes will let's you change the simple combobox styles:
$custom-drop-down-theme: drop-down-theme(
$background-color: #d9f5d6,
$header-text-color: #1a5214,
$item-text-color: #1a5214,
$focused-item-background: #72da67,
$focused-item-text-color: #1a5214,
$hover-item-background: #a0e698,
$hover-item-text-color: #1a5214,
$selected-item-background: #a0e698,
$selected-item-text-color: #1a5214,
$selected-hover-item-background: #72da67,
$selected-hover-item-text-color: #1a5214,
$selected-focus-item-background: #72da67,
$selected-focus-item-text-color: #1a5214,
);
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);
}
Note
The IgxSimpleCombo component uses the IgxOverlay service to hold and display the simple 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 IgxSimpleCombo is box unlike the IgxSelect where it is line.
Demo
Known Issues
- El cuadro combinado simple no tiene entrada para dimensionar su altura. En el futuro, el componente IgxInputGroup expondrá una opción que permite un tamaño personalizado y luego IgxSimpleCombo usará la misma funcionalidad para un estilo adecuado y una mejor coherencia.
- When the simple 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. - When the simple combobox is bound via
ngModeland is marked asrequired,null,undefinedand''values cannot be selected. - Cuando el cuadro combinado simple 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 simple combobox uses igxForOf directive internally hence all igxForOf limitations are valid for the simple combobox. For more details see igxForOf Known Issues section.
API Summary
Componentes 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
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.