Menú desplegable jerárquico de selección múltiple
Los siguientes ejemplos demuestran cómo crear un menú desplegable jerárquico de selección múltiple que permite al usuario seleccionar una o varias opciones de una lista desplegable jerárquica de estilo árbol.
Descripción general del tema
Para la lista desplegable usaremos IgxDropDownComponent así como IgxToggleActionDirective para abrir/cerrar el menú desplegable.
Para visualizar los datos jerárquicos en el menú desplegable, puede utilizar IgxTreeComponent o IgxTreeGridComponent .
El IgxChipComponent
se utiliza para mostrar los elementos seleccionados.
Selección
Para mostrar los nodos/filas seleccionados de la lista, utilice IgxChipComponent
manejando los eventos que notifican los cambios de selección y completan la matriz selectedNodes
/ selectedRows
. Esto se puede hacer suscribiéndose al evento nodeSelection
de IgxTreeComponent y al evento rowSelectionChanging
de IgxTreeGridComponent.
Para eliminar el chip del DOM y anular la selección del elemento del árbol/cuadrícula, debe manejar el evento remove
de IgxChipComponent.
Además, una forma de evitar que el menú desplegable se cierre al eliminar el chip sería verificar la ruta compuesta del evento en busca de un igx-chip
nodo y luego cancelar el evento en el IgxDropDownComponent
's closing
controlador de eventos.
Manifestación
import { AfterViewInit, Component, DoCheck, OnInit, ViewChild,ElementRef } from '@angular/core' ;
import { IBaseChipEventArgs, IgxDropDownComponent, IgxTreeComponent, ITreeNodeSelectionEvent, ConnectedPositioningStrategy, OverlaySettings, IgxButtonDirective, IgxToggleActionDirective, IgxDropDownItemNavigationDirective, IgxIconComponent, IgxChipsAreaComponent, IgxChipComponent, IgxTreeNodeComponent } from 'igniteui-angular' ;
import { COUNTRIES } from './countries' ;
import { NgFor } from '@angular/common' ;
@Component ({
selector : 'app-dropdown-tree-hierarchical-selection' ,
styleUrls : ['./dropdown-tree-hierarchical-selection.component.scss' ],
templateUrl : './dropdown-tree-hierarchical-selection.component.html' ,
imports : [IgxButtonDirective, IgxToggleActionDirective, IgxDropDownItemNavigationDirective, IgxIconComponent, IgxChipsAreaComponent, NgFor, IgxChipComponent, IgxDropDownComponent, IgxTreeComponent, IgxTreeNodeComponent]
})
export class DropdownTreeHierarchicalSelectionComponent implements OnInit , DoCheck , AfterViewInit {
@ViewChild (IgxTreeComponent, { static : true }) public igxTree: IgxTreeComponent;
@ViewChild (IgxDropDownComponent, { static : true }) public igxDropDown: IgxDropDownComponent;
@ViewChild ('button' , { static : true }) public igxButton: ElementRef;
public countries!: any [];
public selectedNodes!: any [];
public ngOnInit(): void {
this .countries = COUNTRIES;
}
public ngAfterViewInit(): void {
requestAnimationFrame(() => {
this ._overlaySettings.target = this .igxButton.nativeElement;
this .igxDropDown.open(this ._overlaySettings);
});
}
public ngDoCheck ( ) {
this .selectedNodes = this .igxTree.nodes?.filter(node => node.selected == true );
}
public onNodeSelection (args: ITreeNodeSelectionEvent ) {
this .selectedNodes = args.newSelection;
}
public chipRemoved (event: IBaseChipEventArgs ) {
this .selectedNodes = this .selectedNodes.filter((node ) => {
if (node.data.ID === event.owner.id){
this .igxTree.deselectAll([node]);
}
return node.data.ID !== event.owner.id;
});
}
public _overlaySettings: OverlaySettings = {
modal : false ,
positionStrategy : new ConnectedPositioningStrategy(),
closeOnOutsideClick : false
};
}
ts コピー <button class ="button" #button igxButton ="contained" [igxToggleAction ]="countriesDropDown"
[igxDropDownItemNavigation ]="countriesDropDown" >
Countries<igx-icon fontSet ="material" > expand_more</igx-icon >
</button >
<div class ="chip-container" >
<igx-chips-area >
<igx-chip *ngFor ="let node of selectedNodes" [id ]="node.data.ID" [removable ]="true" (remove )="chipRemoved($event)" > {{node.data.Name}}</igx-chip >
</igx-chips-area >
</div >
<igx-drop-down #countriesDropDown [height ]="'400px'" [width ]="'250px'" >
<igx-tree #igxTree selection ="BiState" (nodeSelection )="onNodeSelection($event)" >
<igx-tree-node *ngFor ="let country of countries" [data ]="country" [expanded ]="true" [selected ]="true" >
{{ country.Name }}
<igx-tree-node *ngFor ="let city of country.Cities" [data ]="city" >
{{ city.Name }}
</igx-tree-node >
</igx-tree-node >
</igx-tree >
</igx-drop-down >
html コピー .chip-container {
width : 500px ;
overflow : auto;
border : 1px solid #ccc ;
background-color : #FFFBFA ;
display : inline-flex;
margin-left :10px ;
}
igx-chip {
margin-right : 5px ;
margin-bottom : 5px ;
}
.button {
width : 250px ;
border : #ccc ;
}
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.
import { AfterViewInit, Component,ElementRef, OnInit, ViewChild } from '@angular/core' ;
import { IBaseChipEventArgs, IgxDropDownComponent, OverlaySettings, IgxTreeGridComponent, IRowSelectionEventArgs, ConnectedPositioningStrategy, IgxButtonDirective, IgxToggleActionDirective, IgxDropDownItemNavigationDirective, IgxIconComponent, IgxChipsAreaComponent, IgxChipComponent, IgxColumnComponent } from 'igniteui-angular' ;
import { EMPLOYEE_DATA } from './nested-employee-data' ;
import { NgFor } from '@angular/common' ;
@Component ({
selector : 'app-dropdown-tree-grid-hierarchical-selection' ,
styleUrls : ['./dropdown-tree-grid-hierarchical-selection.component.scss' ],
templateUrl : './dropdown-tree-grid-hierarchical-selection.component.html' ,
imports : [IgxButtonDirective, IgxToggleActionDirective, IgxDropDownItemNavigationDirective, IgxIconComponent, IgxChipsAreaComponent, NgFor, IgxChipComponent, IgxDropDownComponent, IgxTreeGridComponent, IgxColumnComponent]
})
export class DropdownTreeGridHierarchicalSelectionComponent implements OnInit , AfterViewInit {
@ViewChild ('treeGrid' , { static : true })
public igxTreeGrid: IgxTreeGridComponent;
@ViewChild (IgxDropDownComponent, { static : true }) public igxDropDown: IgxDropDownComponent;
@ViewChild ('button' , { static : true }) public igxButton: ElementRef;
public employees!: any [];
public selectedRows!: any [];
public ngOnInit(): void {
this .employees = EMPLOYEE_DATA;
this .igxTreeGrid.selectRows([1 ,4 ], true );
this .selectedRows = [];
this .igxTreeGrid.selectedRows.forEach((row ) => this .selectedRows.push(this .employees.find(employee => employee.ID == row)));
}
public ngAfterViewInit(): void {
requestAnimationFrame(() => {
this ._overlaySettings.target = this .igxButton.nativeElement;
this .igxDropDown.open(this ._overlaySettings);
});
}
public onRowSelectionChanging (args: IRowSelectionEventArgs, grid: IgxTreeGridComponent ) {
this .selectedRows = [];
args.newSelection.forEach((val ) => this .selectedRows.push(grid.getRowData(val.ID)));
}
public chipRemoved (event: IBaseChipEventArgs ) {
this .selectedRows = this .selectedRows.filter((row ) => {
if (row.ID === event.owner.id){
this .igxTreeGrid.deselectRows([row.ID]);
}
return row.ID !== event.owner.id;
});
}
public _overlaySettings: OverlaySettings = {
modal : false ,
positionStrategy : new ConnectedPositioningStrategy(),
closeOnOutsideClick : false
};
}
ts コピー <button #button igxButton ="contained" [igxToggleAction ]="employeesDropDown" [igxDropDownItemNavigation ]="employeesDropDown" >
Employees<igx-icon fontSet ="material" > expand_more</igx-icon >
</button >
<div class ="chip-container" >
<igx-chips-area >
<igx-chip *ngFor ="let row of selectedRows" [id ]="row.ID" [removable ]="true" (remove )="chipRemoved($event)" > {{row.Name}}</igx-chip >
</igx-chips-area >
</div >
<igx-drop-down #employeesDropDown [width ]="'300px'" >
<igx-tree-grid #treeGrid igxPreventDocumentScroll [data ]="employees" childDataKey ="Employees" primaryKey ="ID"
width ="100%" height ="400px" [autoGenerate ]="false" [expansionDepth ]="1" [rowSelection ]="'multiple'"
(rowSelectionChanging )="onRowSelectionChanging($event, treeGrid)" >
<igx-column field ="Name" dataType ="string" > </igx-column >
</igx-tree-grid >
</igx-drop-down >
html コピー .chip-container {
width : 500px ;
overflow : auto;
border : 1px solid #ccc ;
background-color : #FFFBFA ;
display : inline-flex;
margin-left :10px ;
}
igx-chip {
margin-right : 5px ;
margin-bottom : 5px ;
}
button {
width : 300px ;
border : #ccc ;
}
scss コピー
Para mostrar el componente desplegable abierto inicialmente, se recomienda establecer el método open como una devolución de llamada del método requestAnimationFrame. Esto asegurará que el árbol DOM se vuelva a pintar y que todos los elementos estén colocados correctamente.
Referencias de API
Recursos adicionales
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.