LIDOR SYSTEMS

Advanced User Interface Controls and Components

Select Multiple Items in Angular TreeView

Created: 21 Aug 2017

There are different ways to select multiple items in IntegralUI TreeView component for Angular. You can select items using mouse and/or keyboard using the CTRL or SHIFT keys. In addition, you can also select items from code.

TreeView component is part of IntegralUI Web
a suite of UI Components for development of web apps

If you have any questions, don't hesitate to contact us at support@lidorsystems.com

In above demo you can choose one of four selection options available. Depending on chosen option, the way tree items are selected changes. Once you select, the list on the right will display a list of all currently selected items.

Selection Options in Angular TreeView

There are four selection options in TreeView component:

  • None - selection is disabled
  • One - only one item is selectable, default option
  • MultiSimple - you can select multiple items using mouse clicks
  • MultiExtended - you can select multiple items using CTRL or SHIFT keys

If you want to prevent selection for all items, the best option is to disable it by setting the selectionMode property value to None. In cases of multiple selection, the best is to use the MultiExtended mode, because it allows you to select items using SHIFT key from the first clicked item to the last. MultiSimple mode allows you to select items using only the mouse, keyboard is not required.

// 
// app.module.ts
//

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { IntegralUIModule } from './integralui/integralui.module';

import { AppComponent }   from './app.component';

@NgModule({
    imports:      [ 
          BrowserModule, 
          FormsModule, 
          IntegralUIModule
    ],
    declarations: [ 
        AppComponent, 
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

// 
// app.component.ts
//

import { Component, ViewContainerRef, ViewChild, ViewEncapsulation } from '@angular/core';
import { IntegralUITreeView } from './integralui/components/integralui.treeview';
import { IntegralUISelectionMode } from '/integralui/components/integralui.core';
import { IntegralUIListBox } from './integralui/components/integralui.listbox';

@Component({
    selector: 'iui-app',
    templateUrl: 'app.template.html',
    styleUrls: ['sample-styles.css'],
    encapsulation: ViewEncapsulation.None
})
export class AppComponent {
    @ViewChild('application', {read: ViewContainerRef}) applicationRef: ViewContainerRef;
    @ViewChild('treeview') treeview: IntegralUITreeView;
    @ViewChild('listbox') listbox: IntegralUIListBox;

    // An array that holds all options in the comboo box
    public comboItems: Array;
    
    // An array that holds a flat list of tree hierarchy
    private flatData: Array;
    
    // An object that holds all items in the TreeView
    public treeItems: Array;

    // An array that holds a list of all selected items
    public selItems: Array;

    // Current selection mode is set to single selection
    public selMode: IntegralUISelectionMode = IntegralUISelectionMode.One;

    public comboStyle: any = {
        general: {
            normal: 'trw-cmb-mst'
        }
    }

    public treeStyle: any = {
        general: {
            normal: 'trw-mst-normal'
        }
    }

    public listStyle: any = {
        general: {
            normal: 'trw-mst-list'
        }
    }

    constructor(){
        // Options to choose from
        this.comboItems = [
          { text: "None" },
          { text: "One" },
          { text: "Multi Simple" },
          { text: "Multi Extended" }
        ];

        // At first TreeView doesn't have any data
        // We will use loadData method to load a flat list into the TreeView after the view is initialized
        this.treeItems = [];

        // Create a tree hierarchy
        this.flatData = [
            { id: 1, text: "Dairy", expanded: false },
            { id: 11, pid: 1, text: "Milk" },
            { id: 12, pid: 1, text: "Butter" },
            { id: 13, pid: 1, text: "Cheese", checked: true },
            { id: 14, pid: 1, text: "Yogurt" },
            { id: 2, text: "Fruits", checked: true },
            { id: 21, pid: 2, text: "Berries", expanded:  false},
            { id: 211, pid: 21, text: "BlackBerries" },
            { id: 212, pid: 21, text: "CranBerries", checked: true },
            { id: 213, pid: 21, text: "StrawBerries" },
            { id: 22, pid: 2, text: "Pits", checked: true },
            { id: 23, pid: 2, text: "Core" },
            { id: 24, pid: 2, text: "Citrus Fruits" },
            { id: 241, pid: 24, text: "Oranges" },
            { id: 242, pid: 24, text: "Lemons", checked: true },
            { id: 25, pid: 2, text: "Melons" },
            { id: 26, pid: 2, text: "Tropical Fruits", expanded: false },
            { id: 261, pid: 26, text: "Avocados", checked: true },
            { id: 262, pid: 26, text: "Bananas", checked: true },
            { id: 263, pid: 26, text: "Dates" },
            { id: 3, text: "Grains" },
            { id: 4, text: "Meat", checked: true },
            { id: 41, pid: 4, text: "Beef" },
            { id: 42, pid: 4, text: "Lamb", expanded: false },
            { id: 421, pid: 42, text: "Lamb Breast" },
            { id: 422, pid: 42, text: "Lamb Leg", checked: true },
            { id: 423, pid: 42, text: "Lamb Ribs" },
            { id: 43, pid: 4, text: "Pork", checked: true },
            { id: 5, text: "Sweets" },
            { id: 6, text: "Vegetables", checked: true },
            { id: 7, text: "Water" }
        ];

        // At first there are no selected items
        this.selItems = [];
    }

    ngAfterViewInit(){
        this.treeview.loadData(this.flatData);
    }

    onComboSelectionChanged(e: any){
        // Whenever an option is selected, update the selection mode of the ListBox
        switch (e.index){
          case 0:
            this.selMode = IntegralUISelectionMode.None;
            break;

          case 2:
            this.selMode = IntegralUISelectionMode.MultiSimple;
            break;

          case 3:
            this.selMode = IntegralUISelectionMode.MultiExtended;
            break;

          default:
            this.selMode = IntegralUISelectionMode.One;
            break;
        }
    } 

}
                            
// 
// app.template.html
//

<div style="float:left">
    <div style="float:right">
        <span style="display:inline-block;padding:10px 5px 5px 0;">Selection Mode: </span>
        <iui-combobox [items]="comboItems" [controlStyle]="comboStyle" [maxDropDownItems]="4" [integralHeight]="true" [selectedIndex]="1" (selectedIndexChanged)="onComboSelectionChanged($event)">
            <iui-item *ngFor="let item of comboItems" [text]="item.text"></iui-item>
        </iui-combobox>
    </div>
    <iui-treeview [items]="treeItems" [controlStyle]="treeStyle" [selectionMode]="selMode" (selectionChanged)="onSelectionChanged($event)" #treeview>
        <ng-template let-item>
              <span class="trw-mst-item-label">{{item.text}}</span>
        </ng-template>
    </iui-treeview>
</div>
<div style="float:left;margin-left:30px;">
  <div style="padding:10px 0 5px 0;">Selected Items:</div>
  <iui-listbox [items]="selItems" [controlStyle]="listStyle" #listbox>
      <iui-listitem *ngFor="let item of selItems">  
          <div class="trw-mst-item-label">{{item.text}}</div>
      </iui-listitem>
  </iui-listbox>
</div>
                            
/*
* sample-styles.css
*/ 

.trw-cmb-mst
{
    display: inline-block;
    float: right;
    width: 200px;
}
.trw-mst-normal
{
    width: 350px;
    height: 400px;
}
.trw-mst-item-label
{
    padding: 5px;
}
.trw-mst-list
{
    width: 350px;
    height: 400px;
}
                            

NOTE During selection process, beforeSelect and afterSelect events are fired, which you can handle in your code and add your own custom actions.

Multi Select using CTRL or SHIFT Keys

When selectionMode property value is set to either MultiSimple or MultiExtended, you can select multiple items.

In MultiSimple mode, you can select multiple items using only the mouse. You can still use the CTRL key, but it is not required.

On the other hand, with MultiExtended mode in order to select items, you need to press and hold CTRL or SHIFT key and click on items. When SHIFT key is pressed, you can select all items between the first and the last clicked item.

Display Selected Items in a Separate List

Whenever selection changes, a list of selected items is internally stored. To retrieve this list, use the getList method with 'selected' parameter. Like in this example, this method is used to update the list on the right, to show all currently selected items in the TreeView component.

onSelectionChanged(e: any){
    // Get the list of currently selected items and display it in the TreeView on the right
    let list: Array = this.treeview.getList('selected');

    this.selItems.length = 0;
    for (let i = 0; i < list.length; i++)
        this.selItems.push({ text: list[i].text });

    this.listbox.updateLayout();
}
                            
<iui-treeview [items]="treeItems" [controlStyle]="treeStyle" [selectionMode]="selMode" (selectionChanged)="onSelectionChanged($event)" #treeview>
    <ng-template let-item>
          <span class="trw-mst-item-label">{{item.text}}</span>
    </ng-template>
</iui-treeview>
                            

Manually Select items

In some cases, you may need to select multiple items from code. For this purpose, the selectItems method is available. At first you need to create an array of items that you want to select, and then apply it to the method, like this:


let list: Array<any> = [];

list.push(this.flatData[1]);
list.push(this.flatData[2]);
list.push(this.flatData[5]);

this.treeview.selectItems(list);
                            

Conclusion

There are different options to select items in TreeView component for Angular. Depending on chosen options, you can disable selection, select one or multiple items. This process is accompanied with events that you can handle in your code and further extend this functionality. When required, you can also select multiple items manually from code.

The TreeView component is part of IntegralUI Web.

Did you Like this Article?


Enter your e-mail address below and you will receive latest articles as well as news on upcoming events and special offers.