Cuadrícula Angular con combinaciones en cascada
La funcionalidad de edición de Grid brinda la oportunidad de utilizar combinaciones en cascada . Al seleccionar el valor en cualquier Combo anterior, los usuarios recibirán solo los datos que sean relevantes para su selección dentro del siguiente Combo.
Descripción general de muestra de cuadrícula Angular con combinaciones en cascada
El siguiente ejemplo demuestra cómo funciona Grid
con Cascading Combos
anidados.
import { Component, OnInit, QueryList, ViewChildren } from '@angular/core' ;
import { IgxSimpleComboComponent, ISimpleComboSelectionChangingEventArgs, IgxGridComponent, IgxColumnComponent, IgxCellTemplateDirective, IgxLinearProgressBarComponent } from 'igniteui-angular' ;
import { Country, getCitiesByCountry, getCountries } from '../../data/cities15000-regions-countries' ;
import { DATA } from '../../data/data' ;
import { IgxPreventDocumentScrollDirective } from '../../directives/prevent-scroll.directive' ;
import { FormsModule } from '@angular/forms' ;
@Component ({
selector : 'grid-cascading-combos' ,
templateUrl : './grid-cascading-combos.component.html' ,
styleUrls : ['./grid-cascading-combos.component.scss' ],
imports : [IgxGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxCellTemplateDirective, IgxSimpleComboComponent, FormsModule, IgxLinearProgressBarComponent]
})
export class GridCascadingCombosComponent implements OnInit {
@ViewChildren (IgxSimpleComboComponent)
public combos: QueryList<IgxSimpleComboComponent>;
public selectedCountryName: string ;
public selectedRegionName: string ;
public selectedCityId: number ;
public countriesData: Country[];
private loadingTime = 0 ;
public data;
public ngOnInit ( ) {
this .data = DATA;
this .countriesData = getCountries([
'United States' ,
'Japan' ,
'United Kingdom'
]);
}
public countryChanging (e: ISimpleComboSelectionChangingEventArgs, cell ) {
const ID = cell.row.data.ID;
cell.row.data.loadingRegion = true ;
const nextRegionCombo = this .combos.filter(
(combo ) => combo.id === 'region-' + ID
)[0 ];
const nextCityCombo = this .combos.filter(
(combo ) => combo.id === 'city-' + ID
)[0 ];
this .clearOldData(cell, nextRegionCombo, nextCityCombo);
this .selectedCountryName = e.newValue;
cell.update(e.newValue ? e.newValue : '' );
if (e.newValue) {
this .loadingTime = 2000 ;
}
setTimeout (() => {
nextRegionCombo.data = getCitiesByCountry([this .selectedCountryName])
.map((c ) => ({ name : c.region, country : c.country }))
.filter((v, i, a ) => a.findIndex((r ) => r.name === v.name) === i);
cell.row.data.loadingRegion = false ;
}, this .loadingTime);
this .selectedRegionName = null ;
this .selectedCityId = null ;
this .loadingTime = 0 ;
}
public regionChanging (e: ISimpleComboSelectionChangingEventArgs, cell ) {
const nextComboID = 'city-' + cell.row.data.ID;
cell.row.data.loadingCity = true ;
const cityCombo = this .combos.filter(
(combo ) => combo.id === nextComboID
)[0 ];
this .clearOldData(cell, null , cityCombo);
this .selectedRegionName = e.newValue;
cell.update(e.newValue ? e.newValue : '' );
if (e.newValue) {
this .loadingTime = 2000 ;
}
setTimeout (() => {
cityCombo.data = getCitiesByCountry([this .selectedCountryName]).filter(
(c ) => c.region === this .selectedRegionName
);
cell.row.data.loadingCity = false ;
}, this .loadingTime);
this .selectedCityId = null ;
this .loadingTime = 0 ;
}
public cityChanging (e: ISimpleComboSelectionChangingEventArgs, cell ) {
cell.update(e.newValue);
this .selectedCityId = e.newValue;
}
private clearOldData (cell, RegionCombo, CityCombo ) {
const nextCellIndex = cell.column.visibleIndex + 1 ;
cell.row.cells[nextCellIndex].update('' );
if (CityCombo !== null ) {
CityCombo.data = [];
}
if (RegionCombo !== null ) {
RegionCombo.data = [];
cell.row.cells[nextCellIndex + 1 ].update('' );
}
}
}
ts コピー <div class ="grid__wrapper" >
<div class ="sample__header" >
<igx-grid [igxPreventDocumentScroll ]="true" #grid1 [data ]="data" [autoGenerate ]="false" width ="100%"
height ="500px" [primaryKey ]="'ID'" >
<igx-column field ="ID" header ="ID" [dataType ]="'number'" width ="50px" >
</igx-column >
<igx-column field ="Country" header ="Country" dataType ="string" width ="220px" >
<ng-template igxCell let-cell ="cell" >
<igx-simple-combo [id ]="'country-' + cell.row.data.ID" [data ]="countriesData"
(selectionChanging )="countryChanging($event, cell)" placeholder ="Choose Country..."
[ngModel ]="cell.value === '' ? undefined : cell.value" [valueKey ]="'name'" [displayKey ]="'name'"
width ="100%" [overlaySettings ]="{ outlet: grid1.outlet }" >
</igx-simple-combo >
</ng-template >
</igx-column >
<igx-column field ="Region" header ="Region" dataType ="string" width ="220px" >
<ng-template igxCell let-cell ="cell" >
<div >
<igx-simple-combo [id ]="'region-' + cell.row.data.ID"
(selectionChanging )="regionChanging($event, cell)" placeholder ="Choose Region..."
[ngModel ]="cell.value === '' ? undefined : cell.value" [valueKey ]="'name'"
[displayKey ]="'name'" [disabled ]="cell.row.cells[1].value === ''" [overlaySettings ]="{ outlet: grid1.outlet }" >
</igx-simple-combo >
@if (cell.row.data.loadingRegion) {
<igx-linear-bar [id ]="'region-progress-' + cell.row.data.ID"
type ="info" [indeterminate ]="true" >
</igx-linear-bar >
}
</div >
</ng-template >
</igx-column >
<igx-column field ="City" header ="City" width ="220px" dataType ="number" >
<ng-template igxCell let-cell ="cell" >
<div >
<igx-simple-combo [id ]="'city-' + cell.row.data.ID" placeholder ="Choose City..."
(selectionChanging )="cityChanging($event, cell)"
[ngModel ]="!cell.value ? undefined : cell.value" [valueKey ]="'id'" [displayKey ]="'name'"
[disabled ]="cell.row.cells[2].value === ''" [overlaySettings ]="{ outlet: grid1.outlet }" >
</igx-simple-combo >
@if (cell.row.data.loadingCity) {
<igx-linear-bar [id ]="'city-progress-' + cell.row.data.ID"
type ="info" [indeterminate ]="true" >
</igx-linear-bar >
}
</div >
</ng-template >
</igx-column >
</igx-grid >
</div >
</div >
html コピー .grid__wrapper {
--ig-size: var(--ig-size-medium);
padding : 16px ;
igx-simple-combo {
--ig-size: var(--ig-size-small);
}
}
.dialogNewRecord {
> * {
margin-bottom : 8px ;
&:last-child {
margin-bottom : 0 ;
}
}
#discontinued {
margin-top : 15px ;
}
}
:host {
::ng-deep{
.igx-grid {
margin-top: 10px ;
}
.igx-checkbox {
margin-top : 5px ;
margin-bottom : 5px ;
padding-top : 8px ;
padding-bottom : 5px ;
}
.reorderLevelInput {
color : black;
width : 100% ;
}
@media screen and (max-width : 934px ) {
.igx-grid {
overflow-x : none;
}
}
}
}
.default-theme {
.addProdBtn .igx-button--contained {
background-color : lightgrey;
color : black;
&:hover {
background-color : rgba(0 , 0 , 0 , 0.26 )
}
}
}
scss コピー
¿Te gusta esta muestra? Obtenga acceso a nuestro kit de herramientas de Ignite UI for Angular completo y comience a crear sus propias aplicaciones en minutos. Descárgalo gratis.
Configuración
Para habilitar la edición de columnas, asegúrese de que la propiedad editable
esté configurada en verdadero .
Una vez que la edición de columnas esté habilitada, puede comenzar agregando su cuadro combinado de selección única . Tenga en cuenta que aquí, para tener solo una selección disponible, deberá usar igxSimpleCombo en lugar de modificar igxCombo.
Para comenzar con el componente Simple ComboBox , primero debe importar IgxSimpleComboModule
en su archivo app.module.ts :
import { IgxSimpleComboModule } from 'igniteui-angular' ;
@NgModule ({
imports : [
...
IgxSimpleComboModule,
...
]
})
export class AppModule {}
typescript
Luego, en la plantilla, debes vincular los combos igx-simple-combo a algunos datos.
displayKey
: obligatorio para matrices de objetos : especifica qué propiedad se utilizará para el texto de los elementos. Si no se especifica ningún valor para displayKey , el cuadro combinado simple utilizará la valueKey
especificada (si corresponde).
export class MySimpleComboComponent implements OnInit {
public countriesData: Country[];
public selectedCountry: Country;
public selectedCity: City;
public ngOnInit ( ) {
this .countriesData = getCountries([
'United States' ,
'Japan' ,
'United Kingdom'
]);
}
}
typescript
Para manejar el cambio de selección, necesitamos 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. Por lo tanto, filtrará los valores en función de la selección del combo anterior.
<igx-combo [data ]="countriesData" (selectionChanging )="countryChanging($event)" > </igx-combo >
html
public countryChanging (event: IComboSelectionChangeEventArgs ) {
if (event.added.length) {
event.newSelection = event.added;
}
}
typescript
Y, por último, agregar el Progreso lineal , que se requiere al cargar la lista de datos. La id
es necesaria para establecer el valor del atributo id
.
<igx-linear-bar
[id ]="'region-progress-' + cell.row.data.ID"
[style.visibility ]="'hidden'"
type ="info" [indeterminate ]="true" >
</igx-linear-bar >
html
Resumen de API
Recursos adicionales