Descripción general del árbol Web Components

    Ignite UI for Web Components Tree, también conocido como componente TreeView, es un control de alto rendimiento que visualiza estructuras de datos expandibles dentro de una interfaz de usuario similar a un árbol, lo que le permite aplicar carga a petición para los elementos secundarios. El árbol de Ignite UI for Web Components también proporciona características como la expansión y contracción de nodos, la navegación de aplicaciones anidadas Ignite UI for Web Components los nodos del árbol se pueden generar manualmente o a partir de una fuente de datos enlazada.

    Para los usuarios finales, esto significa que pueden navegar fácilmente a través de diferentes páginas de aplicaciones, usar selecciones, casillas de verificación, agregar textos, íconos, imágenes y más.

    The Ignite UI for Web Components Tree component allows users to represent hierarchical data in a tree-view structure, maintaining parent-child relationships, as well as to define static tree-view structure without a corresponding data model. Its primary purpose is to allow end-users to visualize and navigate within hierarchical data structures. The IgcTreeComponent component also provides load on demand capabilities, item activation, multiple and cascade selection of items through built-in checkboxes, built-in keyboard navigation and more.

    Web Components Tree Example

    En este ejemplo básico de árbol de Ignite UI for Web Components, puede ver cómo definir un árbol y sus elementos especificando la jerarquía de elementos.

    How to Use Ignite UI for Web Components Tree With Ignite UI

    En primer lugar, debe instalar el Ignite UI for Web Components ejecutando el siguiente comando:

    npm install igniteui-webcomponents
    

    Before using the IgcTreeComponent, you need to register it as follows:

    import { defineComponents, IgcTreeComponent } from 'igniteui-webcomponents';
    defineComponents(IgcTreeComponent);
    

    Para una introducción completa al Ignite UI for Web Components, lee el tema Empezar.

    The simplest way to start using the IgcTreeComponent is as follows:

    Declaring a tree

    IgcTreeItemComponent is the representation of every item that belongs to the IgcTreeComponent. Items provide disabled, active, selected and expanded properties, which give you opportunity to configure the states of the item as per your requirement. The value property can be used to add a reference to the data entry the item represents.

    Los artículos se pueden declarar utilizando uno de los siguientes enfoques.

    • Declarar el árbol y sus elementos especificando la jerarquía de elementos e iterando a través de un conjunto de datos
    <igc-tree>
        ${data.map((x) => html`
            <igc-tree-item .value=${x} .expanded=${x.expanded} .label=${x.label}>
                  ${x.children.map((y) => html`
                      <igc-tree-item .value=${y} .expanded=${y.expanded}>
                          <span slot="label">${y.label}</slot>
                      </igc-tree-item>
                  `
            </igc-tree-item>
        `
    </igc-tree>
    

    Los elementos se pueden vincular a un modelo de datos para que sus estados expandidos y seleccionados también se reflejen en los datos subyacentes.

    • Declarar un árbol creando elementos estáticos independientes

    In order to render a tree you do not necessarily need a data set - individual items can be created without an underlying data model using the exposed label property or provide a custom slot content for the IgcTreeItemComponent label.

    <igc-tree>
        <igc-tree-item>
            <div slot="label">
                I am a parent item 1
                <img src="hard_coded_src.webb" alt="Alt Text">
            </div>
            <igc-tree-item label="I am a child item 1">
            </igc-tree-item>
        </igc-tree-item>
    
        <igc-tree-item>
            <div slot="label">
                I am a parent item 2
                <img src="hard_coded_src.webb" alt="Alt Text">
            </div>
            <igc-tree-item label="I am a child item 1">
            </igc-tree-item>
        </igc-tree-item>
    </igc-tree>
    

    [!Note] You can provide a custom slot content for each IgcTreeItemComponent's indentation, expansion and label area respectively using the provided indentation, indicator and label slots.

    Item Interactions

    IgcTreeItemComponent could be expanded or collapsed:

    • Haciendo clic en el indicador de expansión del objeto (comportamiento por defecto).
    • by clicking on the item if the IgcTreeComponent toggleNodeOnClick property is set to true.
    <igc-tree toggle-node-on-click="true">
        <igc-tree-item label="North America">
            <igc-tree-item label="United States"></igc-tree-item>
            <igc-tree-item label="Canada"></igc-tree-item>
            <igc-tree-item label="Mexico"></igc-tree-item>
        </igc-tree-item>
        <igc-tree-item label="South America">
            <igc-tree-item label="Brazil"></igc-tree-item>
        </igc-tree-item>
    </igc-tree>
    

    By default, multiple items could be expanded at the same time. In order to change this behavior and allow expanding only single branch at a time, the singleBranchExpand property could be enabled. This way when an item is expanded, all of the others already expanded branches in the same level will be collapsed.

    <igc-tree single-branch-expand="true">
        <igc-tree-item label="North America">
            <igc-tree-item label="United States"></igc-tree-item>
            <igc-tree-item label="Canada"></igc-tree-item>
            <igc-tree-item label="Mexico"></igc-tree-item>
        </igc-tree-item>
        <igc-tree-item label="South America">
            <igc-tree-item label="Brazil"></igc-tree-item>
        </igc-tree-item>
    </igc-tree>
    

    In addition, the IgcTreeComponent provides the following API methods for item interactions:

    • expand - expands all items. If an items array is passed, expands only the specified items.
    • collapse - collapses all items. If an items array is passed, collapses only the specified items.
    • IgcSelectComponent - selects all items. If an items array is passed, selects only the specified items. Does not emit selection event.
    • Tree.Deselect - deselects all items. If an items array is passed, deselects only the specified items. Does not emit selection event.

    Web Components Tree Selection

    In order to setup item selection in the Ignite UI for Web Components Tree component, you just need to set its selection property. This property accepts the following three modes: None, Multiple and Cascade. Below we will take a look at each of them in more detail.

    None

    In the IgcTreeComponent by default item selection is disabled. Users cannot select or deselect an item through UI interaction, but these actions can still be completed through the provided API method.

    Multiple

    To enable multiple item selection in the IgcTreeComponent just set the selection property to multiple. This will render a checkbox for every item. Each item has two states - selected or not. This mode supports multiple selection.

    <igc-tree selection="multiple">
    </igc-tree>
    

    Cascade

    To enable cascade item selection in the IgcTreeComponent, just set the selection property to cascade. This will render a checkbox for every item.

    <igc-tree selection="Cascade">
    </igc-tree>
    

    En este modo, el estado de selección de un padre depende completamente del estado de selección de sus hijos. Cuando un padre tiene algunos hijos seleccionados y algunos no seleccionados, su casilla de verificación está en un estado indeterminado.

    Keyboard Navigation

    Keyboard navigation in IgcTreeComponent provides a rich variety of keyboard interactions for the user. This functionality is enabled by default and allows users to navigate through the items.

    The IgcTreeComponent navigation is compliant with W3C accessibility standards and convenient to use.

    Combinaciones de teclas

    • : navega al siguiente elemento visible. Marca el elemento como activo. No hace nada si está en el ÚLTIMO elemento.
    • CTRL + - navega al siguiente elemento visible. No hace nada si está en el ÚLTIMO artículo.
    • - navega al elemento visible anterior. Marca el elemento como activo. No hace nada si está en el PRIMER elemento.
    • CTRL + - navega al elemento visible anterior. No hace nada si está en el PRIMER artículo.
    • : en un elemento principal expandido, lo contrae. Si el elemento está contraído o no tiene hijos, se mueve a su elemento principal. No hace nada si no hay ningún elemento principal.
    • - en un elemento principal expandido, navega al primer elemento secundario del elemento. Si se encuentra en un elemento principal contraído, lo expande. No hace nada si el artículo no tiene hijos.
    • HOME- navega al PRIMER elemento.
    • END- navega hasta el ÚLTIMO elemento visible.
    • TAB- navega al siguiente elemento enfocable en la página, fuera del árbol.
    • SHIFT + TAB- navega al elemento enfocable anterior en la página, fuera del árbol.
    • SPACE- alterna la selección del elemento actual. Marca el nodo como activo.
    • SHIFT + SPACE- alterna la selección de todos los elementos entre el activo y el que presiona Espacio mientras se mantiene presionado SHIFT si la selección está habilitada.
    • ENTER- Activa el elemento enfocado. Si el elemento tiene un vínculo, abre el vínculo.
    • *: expande el artículo y todos los artículos hermanos en el mismo nivel.

    Cuando la selección está habilitada, la selección de elementos por parte del usuario final solo se permite a través de la casilla de verificación representada. Dado que ambos tipos de selección permiten selección múltiple, están disponibles las siguientes interacciones con el mouse y el teclado:

    • Hacer clic: cuando se realiza en la casilla de verificación del elemento, alterna la selección del elemento si la selección está habilitada. De lo contrario, enfoca el elemento.
    • SHIFT + Click- cuando se realiza en la casilla de verificación del elemento, alterna la selección de todos los elementos entre el activo y el que se hace clic mientras se mantiene presionada SHIFT si la selección está habilitada

    Web Components Tree Load On Demand

    El árbol de Ignite UI for Web Components se puede representar de tal manera que requiera que se recupere la cantidad mínima de datos del servidor para que el usuario pueda verlos lo más rápido posible. Con este enfoque de carga dinámica de datos, solo después de que el usuario expanda un elemento, se recuperarán los elementos secundarios de ese elemento primario en particular. Este mecanismo, también conocido como Load on Demand, se puede configurar fácilmente para trabajar con cualquier dato remoto.

    Después de que el usuario hace clic en el icono de expansión, se reemplaza por un indicador de carga. Cuando la propiedad de carga se resuelve en falsa, el indicador de carga desaparece y se cargan los elementos secundarios.

    You can provide a custom slot content for the loading area using the loadingIndicator slot. If such slot is not defined, the IgcCircularProgressComponent is used.

    Load On Demand With Virtualization

    La carga de un mayor número de elementos secundarios a petición en el árbol de Ignite UI for Web Components podría afectar negativamente al rendimiento, ya que los elementos del árbol se definen de forma declarativa por diseño. En la siguiente demostración se muestra cómo se puede usar la biblioteca @lit-labs/virtualizer para representar los elementos del árbol secundario en un contenedor virtualizado. El resultado es un rendimiento mejorado, ya que solo se representa en el DOM la parte visible de los elementos secundarios.

    Styling

    You can change the appearance of the IgcTreeItemComponent, by using some of the exposed CSS parts listed below:

    Nombre de la pieza Descripción
    wrapper El contenedor del elemento del árbol.
    selected Indica el estado seleccionado. Se aplica awrapper.
    focused Indica estado enfocado. Se aplica awrapper.
    active Indica un estado activo. Se aplica awrapper.
    indicator El indicador de expansión del elemento del árbol.
    label El contenido del elemento del árbol.
    text El elemento del árbol mostraba texto.
    select La casilla de verificación del elemento del árbol cuando la selección está habilitada.

    Using these CSS parts we can customize thе appearance of the IgcTreeComponent component like this:

    igc-tree-item::part(active) {
      background: var(--ig-secondary-500);
      color: var(--ig-secondary-500-contrast);
    }
    

    API References

    Additional Resources