Combo Box

The ComboBox CellType represents a combo box cell. This can be useful when you want to add restricted lists that users can select items from, such as when entering data on a form.

To create a combo box cell, follow this example: You can use the editorValueType method to get and set the value that is written to the underlying data model. The editor value type is an EditorValueType enumeration. text: Writes to the model the text value of the selected item. index: Writes to the model the index of the selected item. value: Writes to the model the corresponding data value of the selected item. The different editorValueType settings create different types of editor values. The combo box's value depends on items for the drop-down list in the combo box. You can use the items method to get and set the items. For example: You can also use the dataBinding method to bind the combo box to a data source. The data source will replace the items in the combo box in runtime. For example: Use the editable method to set whether the user can type in the combo box editor. The default value is false; only selection is allowed. For example: You can use the itemHeight method to set the height of each item in the drop-down list. For example: Use the allowFloat method to set whether to allow the drop-down list to float outside the Spread.
import { Component, NgModule, enableProdMode } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { SpreadSheetsModule } from '@mescius/spread-sheets-angular'; import GC from '@mescius/spread-sheets'; import "@mescius/spread-sheets-tablesheet"; import './styles.css'; const spreadNS = GC.Spread.Sheets; class Country { value: string; text: string; shortName: string; fullName: string; constructor(shortName: string, fullName: string) { this.value = this.shortName = shortName; this.text = this.fullName = fullName; } } @Component({ selector: 'app-component', templateUrl: 'src/app.component.html' }) export class AppComponent { hostStyle = { width: 'calc(100% - 280px)', height: '100%', overflow: 'hidden', float: 'left' }; editorValueType = 0; itemsText = ''; itemsValue = ''; itemHeight = 0; editable = false; disabled = false; editorValueTypeList = Object.keys(GC.Spread.Sheets.CellTypes.EditorValueType).filter(key => isNaN(Number(key))); spread: GC.Spread.Sheets.Workbook; allowFloat: true; bindingType:number= 0; dataSourceType:number= 0; tableName=''; textColumn=''; valueColumn=''; dataSource=''; text=''; value=''; async initSpread($event: any) { this.spread = $event.spread; this.spread.suspendPaint(); const loadingTip = addLoadingTip(); const res = await fetch('$DEMOROOT$/en/sample/features/cells/cell-types/combobox/spread.json'); await this.spread.fromJSON(await res.json()); this.spread.setSheetCount(2); var sheet1 = this.spread.getSheet(0); this.initStaticItemsSheet(sheet1); var sheet2 = this.spread.getSheet(1); this.initDataBindingItemsSheet(sheet2); this.fetchDataSource(this.spread); this.spread.resumePaint(); loadingTip.remove(); } fetchDataSource(spread:GC.Spread.Sheets.Workbook) { const productsSheets = spread.addSheetTab(0, 'Products', GC.Spread.Sheets.SheetType.tableSheet); productsSheets.options.allowAddNew = false; const productsTable = spread.dataManager().tables.Products; productsTable.fetch().then(() => { var view = productsTable.addView("myView", Object.keys(productsTable.columns).map(c => ({ value: c, width: 150 }))); productsSheets.setDataView(view); }); const customerSheets = spread.addSheetTab(1, 'Customers', GC.Spread.Sheets.SheetType.tableSheet); customerSheets.options.allowAddNew = false; const customersTable = spread.dataManager().tables.Customers; customersTable.fetch().then(() => { var view = customersTable.addView("myView", Object.keys(customersTable.columns).map(c => ({ value: c, width: 150 }))); customerSheets.setDataView(view); }); const employeesSheets = spread.addSheetTab(2, 'Employees', GC.Spread.Sheets.SheetType.tableSheet); employeesSheets.options.allowAddNew = false; const employeesTable = spread.dataManager().tables.Employees; employeesTable.fetch().then(() => { var view = employeesTable.addView("myView", Object.keys(employeesTable.columns).map(c => ({ value: c, width: 150 }))); employeesSheets.setDataView(view); }); spread.setActiveSheetIndex(0); } propertyChange(e: MouseEvent, settings?: any) { const sheet = this.spread.getActiveSheet(); const sels = sheet.getSelections(); if (sels && sels.length > 0) { const sel = this.getActualRange(sels[0], sheet.getRowCount(), sheet.getColumnCount()); const comboBoxCellType = sheet.getCellType(sel.row, sel.col); if (!(comboBoxCellType instanceof spreadNS.CellTypes.ComboBox)) { this.disabled = true; return; } if (!settings) { this.disabled = false; this.editorValueType = comboBoxCellType.editorValueType(); const items = comboBoxCellType.items(); const { texts, values } = this.getTextAndValueStringArray(items); this.itemsText = texts; this.itemsValue = values; this.editable = comboBoxCellType.editable(); this.itemHeight = comboBoxCellType.itemHeight(); this.allowFloat = comboBoxCellType.allowFloat(); const dataBinding = comboBoxCellType.dataBinding(); if(!dataBinding){ this.bindingType = 0; } else{ this.bindingType = 1; } const dataBindingEditorValue = dataBindingToDataBindingEditorValue(dataBinding, this.spread); this.dataSourceType = dataBindingEditorValue.dataSourceType; this.tableName = dataBindingEditorValue.tableName; this.textColumn = dataBindingEditorValue.textColumn; this.valueColumn = dataBindingEditorValue.valueColumn; this.dataSource = dataBindingEditorValue.dataSource; this.text = dataBindingEditorValue.text; this.value = dataBindingEditorValue.value; } else { comboBoxCellType.editorValueType(Number(this.editorValueType)); const itemsText = this.itemsText.split(","); const itemsValue = this.itemsValue.split(","); const itemsLength = itemsText.length > itemsValue.length ? itemsText.length : itemsValue.length; const items = this.getTextAndValueArray(itemsText, itemsValue, itemsLength); comboBoxCellType.items(items); comboBoxCellType.editable(this.editable); comboBoxCellType.allowFloat(this.allowFloat); const itemHeight = Number(this.itemHeight); if (!isNaN(itemHeight) && itemHeight > 0) { comboBoxCellType.itemHeight(itemHeight); } if (+this.bindingType === 1) { const dataBinding = dataBindingEditorValueToDataBinding( { dataSourceType:this.dataSourceType, tableName:this.tableName, textColumn:this.textColumn, valueColumn:this.valueColumn, dataSource:this.dataSource, text:this.text, value:this.value }); comboBoxCellType.dataBinding(dataBinding); }else{ comboBoxCellType.dataBinding(null); } } } sheet.repaint(); } onTableNameChanged($event: Event){ const columns = getColumns(this.tableName,this.spread); const firstColumn = columns[0]; this.textColumn = firstColumn; this.valueColumn = firstColumn; } getActualRange(range: GC.Spread.Sheets.Range, maxRowCount: number, maxColCount: number) { const row = range.row < 0 ? 0 : range.row; const col = range.col < 0 ? 0 : range.col; const rowCount = range.rowCount < 0 ? maxRowCount : range.rowCount; const colCount = range.colCount < 0 ? maxColCount : range.colCount; return new spreadNS.Range(row, col, rowCount, colCount); } getTextAndValueStringArray(items: any[]) { let texts = '', values = ''; for (let i = 0, len = items.length; i < len; i++) { const item = items[i]; if (!item) { continue; } if (item.text) { texts += item.text + ','; } if (item.value) { values += item.value + ','; } } texts = texts.slice(0, texts.length - 1); values = values.slice(0, values.length - 1); return { texts, values }; } getTextAndValueArray(itemsText: string[], itemsValue: string[], itemsLength: number) { const items = []; for (let count = 0; count < itemsLength; count++) { const t = itemsText.length > count && itemsText[0] != "" ? itemsText[count] : undefined; const v = itemsValue.length > count && itemsValue[0] != "" ? itemsValue[count] : undefined; if (t != undefined && v != undefined) { items[count] = { text: t, value: v }; } else if (t != undefined) { items[count] = { text: t }; } else if (v != undefined) { items[count] = { value: v }; } } return items; } initStaticItemsSheet(sheet: GC.Spread.Sheets.Worksheet) { sheet.name("Static-Items"); sheet.bind(spreadNS.Events.SelectionChanged, (e:any) => this.propertyChange(e)); sheet.suspendPaint(); sheet.setColumnWidth(2, 120); sheet.setColumnWidth(1, 200); var combo = new spreadNS.CellTypes.ComboBox(); combo.items([{ text: "Oranges", value: "11k" }, { text: "Apples", value: "15k" }, { text: "Grape", value: "100k" }]) .editorValueType(spreadNS.CellTypes.EditorValueType.text); sheet.setValue(0, 3, "Result:"); sheet.getCell(1, 2, spreadNS.SheetArea.viewport).cellType(combo).value("Apples"); sheet.setValue(1, 1, "ComboBoxCellType"); sheet.setFormula(1, 3, "=C2"); var editableCombo = new spreadNS.CellTypes.ComboBox(), data = [new Country("CN", "China"), new Country("JP", "Japan"), new Country("US", "United States")]; editableCombo.editable(true) .items(data) .itemHeight(24) .editorValueType(spreadNS.CellTypes.EditorValueType.value); sheet.getCell(3, 2, spreadNS.SheetArea.viewport).cellType(editableCombo).value("US"); sheet.setValue(3, 1, "Editable ComboBoxCellType"); sheet.setFormula(3, 3, "=C4"); var allowFloatCombo = new spreadNS.CellTypes.ComboBox(); allowFloatCombo.items(Array.from({ length: 100 }, (_, index) => { return { text: index + 1, value: index + 1 } })); sheet.getCell(22, 2).cellType(allowFloatCombo); sheet.setValue(22, 1, "Try Allow Float ComBoxCellType"); sheet.setActiveCell(1, 2); this.propertyChange(null); sheet.resumePaint(); } initDataBindingItemsSheet(sheet: GC.Spread.Sheets.Worksheet) { sheet.name("Binding-Items"); sheet.bind(spreadNS.Events.SelectionChanged, (e:any) => this.propertyChange(e)); sheet.suspendPaint(); sheet.setColumnWidth(1, 200); sheet.setColumnWidth(2, 200); sheet.setColumnWidth(3, 200); //--------------------Binding to Table-------------------- var combo = new spreadNS.CellTypes.ComboBox(); combo.dataBinding({ dataSource: "Products", text: "productName", value: "productId" }); combo.editorValueType(spreadNS.CellTypes.EditorValueType.text); sheet.setValue(0, 3, "Result:"); sheet.getCell(1, 2, spreadNS.SheetArea.viewport).cellType(combo).value("Chang"); sheet.setValue(1, 1, "Binding to Table"); sheet.setFormula(1, 3, "=C2"); //--------------------Binding to a formula-------------------- var editableCombo = new spreadNS.CellTypes.ComboBox(); editableCombo.editable(true) .dataBinding({ dataSource: '=SORT(UNIQUE(QUERY("Products", {"productName","productId"})))', text: 0, value: 1 }) .itemHeight(24) .editorValueType(spreadNS.CellTypes.EditorValueType.value); sheet.getCell(3, 2, spreadNS.SheetArea.viewport).cellType(editableCombo).value(1); sheet.setValue(3, 1, "Binding to a formula"); sheet.setFormula(3, 3, "=C4"); //--------------------Binding to a range-------------------- sheet.setArray(6, 6, [["Oranges", "11k"], ["Apples", "15k"], ["Grape", "100k"]]) combo = new spreadNS.CellTypes.ComboBox(); combo.editorValueType(spreadNS.CellTypes.EditorValueType.value); combo.dataBinding({ dataSource: "'Binding-Items'!G7:H9", text: 0, value: 1 }); sheet.getCell(5, 2, spreadNS.SheetArea.viewport).cellType(combo).value("15k"); sheet.setValue(5, 1, "Binding to range"); sheet.setFormula(5, 3, "=C6"); sheet.setActiveCell(1, 2); this.propertyChange(null); sheet.resumePaint(); } tableNames():string[]{ return getDataTables(this.spread); } columnNames():string[]{ return getColumns(this.tableName,this.spread); } } function addLoadingTip() { const div = document.createElement('div'); div.style.position = 'absolute'; div.style.inset = '0'; div.style.display = 'flex'; div.style.alignItems = 'center'; div.style.justifyContent = 'center'; div.style.background = 'white'; div.style.zIndex = '100'; div.textContent = 'Loading data from server ...'; document.body.appendChild(div); return div; } function dataBindingToDataBindingEditorValue(dataBinding:any, workBook:GC.Spread.Sheets.Workbook) { let dataBindingEditorValue; const defDataSource = getDefaultDataSource(workBook); if (!dataBinding) { dataBindingEditorValue = defDataSource; } else { const dataSourceType = isDataTable(dataBinding.dataSource, workBook) ? 0 : 1; if (dataSourceType === 0) { dataBindingEditorValue = { dataSourceType: dataSourceType, tableName: dataBinding.dataSource, textColumn: dataBinding.text, valueColumn: dataBinding.value, }; } else { // custom dataBindingEditorValue = { ...defDataSource, dataSourceType: dataSourceType, dataSource: dataBinding.dataSource, text: dataBinding.text, value: dataBinding.value, }; } } return dataBindingEditorValue; } function getDefaultDataSource(workBook:GC.Spread.Sheets.Workbook) { const tables = getDataTables(workBook); if (tables.length === 0) { return { dataSourceType: 0 }; } const column = getColumns(tables[0], workBook)[0]; return { dataSourceType: 0, tableName: tables[0], textColumn: column, valueColumn: column }; } function dataBindingEditorValueToDataBinding(uiData:any) { if (+uiData.dataSourceType === 0) { return { dataSource: uiData.tableName, text: uiData.textColumn, value: uiData.valueColumn }; } else { return { dataSource: uiData.dataSource, text: uiData.text, value: uiData.value }; } } function isDataTable(table:string, workBook:GC.Spread.Sheets.Workbook) { const lowerTableName = table.toLowerCase(); return getDataTables(workBook).some((t) => t.toLowerCase() === lowerTableName); } function getDataTables(workBook:GC.Spread.Sheets.Workbook) { if (!workBook) { return []; } const dataManager = workBook.dataManager(); if (!dataManager) { return []; } const tables = workBook.dataManager().tables; if (!tables) { return []; } return Object.keys(tables); } function getColumns(tableName:string, workBook:GC.Spread.Sheets.Workbook) { if (!workBook) { return []; } const tables = workBook.dataManager().tables; if (!tables) { return []; } const table = getTableIgnoreCase(tables, tableName); if (!table) { return []; } return Object.keys(table.columns); } function getTableIgnoreCase(tables:any, tableName:string) { if(!tableName){ return tables[0]; } const lowerTableName = tableName.toLowerCase(); for (const key in tables) { if (tables.hasOwnProperty(key) && key.toLowerCase() === lowerTableName) { return tables[key]; } } return null; } @NgModule({ imports: [BrowserModule, SpreadSheetsModule, FormsModule], declarations: [AppComponent], exports: [AppComponent], bootstrap: [AppComponent] }) export class AppModule { } enableProdMode(); // Bootstrap application with hash style navigation and global services. platformBrowserDynamic().bootstrapModule(AppModule);
<!doctype html> <html style="height:100%;font-size:14px;"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="$DEMOROOT$/en/angular/node_modules/@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css"> <!-- Polyfills --> <script src="$DEMOROOT$/en/angular/node_modules/core-js/client/shim.min.js"></script> <script src="$DEMOROOT$/en/angular/node_modules/zone.js/fesm2015/zone.min.js"></script> <!-- SystemJS --> <script src="$DEMOROOT$/en/angular/node_modules/systemjs/dist/system.js"></script> <script src="systemjs.config.js"></script> <script> // workaround to load 'rxjs/operators' from the rxjs bundle System.import('rxjs').then(function (m) { System.import('@angular/compiler'); System.set(SystemJS.resolveSync('rxjs/operators'), System.newModule(m.operators)); System.import('$DEMOROOT$/en/lib/angular/license.ts'); System.import('./src/app.component'); }); </script> </head> <body> <app-component></app-component> </body> </html>
<div class="sample-tutorial"> <gc-spread-sheets [hostStyle]="hostStyle" (workbookInitialized)="initSpread($event)"> <gc-worksheet></gc-worksheet> </gc-spread-sheets> <div class="options-container"> <label>Select one of the combo box cells in Spread and edit its options with these text boxes.</label> <div class="option-row"> <label>Editor Value Type:</label> <select id="editorValueType" [(ngModel)]="editorValueType"> <option *ngFor="let key of editorValueTypeList, index as i" [value]="i">{{ key.charAt(0).toUpperCase() + key.slice(1) }}</option> </select> </div> <div class="option-row"> <label>Binding Type:</label> <select id="binding-type" [(ngModel)]="bindingType"> <option *ngFor="let key of ['Static Items','Data Binding'], index as i" [value]="i">{{ key }}</option> </select> </div> <div *ngIf="bindingType==0"> <div class="option-row"> <label for="itemsText">Items Text:</label> <input id="itemsText" type="text" [(ngModel)]="itemsText" /> </div> <div class="option-row"> <label for="itemsValue">Items Value:</label> <input id="itemsValue" type="text" [(ngModel)]="itemsValue" /> </div> </div> <div *ngIf="bindingType==1"> <div class="option-row"> <label>Data Source Type:</label> <select id="data-source-type" [(ngModel)]="dataSourceType"> <option *ngFor="let key of ['Table','Custom'], index as i" [value]="i">{{ key }}</option> </select> </div> <div *ngIf="dataSourceType==0"> <div class="option-row"> <label >Data Source:</label> <select id="selComboDataSource" [(ngModel)]="tableName" (change)="onTableNameChanged($event)"> <option *ngFor="let key of tableNames()" [value]="key" >{{ key }}</option> </select> </div> <div class="option-row"> <label>Binding Text:</label> <select id="selComboText" [(ngModel)]="textColumn"> <option *ngFor="let key of columnNames()" [value]="key" >{{ key }}</option> </select> </div> <div class="option-row"> <label>Binding Value:</label> <select id="selComboValue" [(ngModel)]="valueColumn"> <option *ngFor="let key of columnNames()" [value]="key" >{{ key }}</option> </select> </div> </div> <div *ngIf="dataSourceType==1"> <div class="option-row"> <label >Data Source:</label> <input id="txtFormula" type="text" [(ngModel)]="dataSource" /> </div> <div class="option-row"> <label>Binding Text:</label> <input id="txtText" type="text" [(ngModel)]="text" /> </div> <div class="option-row"> <label>Binding Value:</label> <input id="txtValue" type="text" [(ngModel)]="value" /> </div> </div> </div> <div class="option-row"> <label for="itemHeight">Item Height:</label> <input id="itemHeight" type="text" [(ngModel)]="itemHeight" /> </div> <div class="option-row"> <input id="editable" type="checkbox" [(ngModel)]="editable" /> <label for="editable">Editable:</label> </div> <div class="option-row"> <input id="allowFloat" type="checkbox" [(ngModel)]="allowFloat" /> <label for="allowFloat">Allow Float:</label> </div> <div class="option-row"> <input type="button" id="setProperty" value="Update" [disabled]="disabled" (click)="propertyChange($event, true)" /> </div> </div> </div>
export function getData() { return [ { name: "Stoves S0", line: "Washers", color: "Green", discontinued: true, rating: "Average" }, { name: "Computers C1", line: "Washers", color: "Green", discontinued: true, rating: "Average" }, { name: "Washers W3", line: "Washers", color: "Green", discontinued: true, rating: "Average" } ] }
.sample-tutorial { position: relative; height: 100%; overflow: hidden; } .sample-spreadsheets { width: calc(100% - 280px); height: 90%; overflow: hidden; float: left; } .options-container { float: right; width: 280px; overflow: auto; padding: 12px; height: 100%; box-sizing: border-box; background: #fbfbfb; } .option-row{ padding-bottom: 12px; } label { padding-bottom: 4px; display: block; } input, select { width: 100%; padding: 4px 8px; box-sizing: border-box; } input[type=checkbox] { width: auto; } input[type=checkbox] + label { display: inline-block; width: auto; user-select: none; } body { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }
(function (global) { System.config({ transpiler: 'ts', typescriptOptions: { tsconfig: true }, meta: { 'typescript': { "exports": "ts" }, '*.css': { loader: 'css' } }, paths: { // paths serve as alias 'npm:': 'node_modules/' }, // map tells the System loader where to look for things map: { 'core-js': 'npm:core-js/client/shim.min.js', 'zone': 'npm:zone.js/fesm2015/zone.min.js', 'rxjs': 'npm:rxjs/dist/bundles/rxjs.umd.min.js', '@angular/core': 'npm:@angular/core/fesm2022', '@angular/common': 'npm:@angular/common/fesm2022/common.mjs', '@angular/compiler': 'npm:@angular/compiler/fesm2022/compiler.mjs', '@angular/platform-browser': 'npm:@angular/platform-browser/fesm2022/platform-browser.mjs', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/fesm2022/platform-browser-dynamic.mjs', '@angular/common/http': 'npm:@angular/common/fesm2022/http.mjs', '@angular/router': 'npm:@angular/router/fesm2022/router.mjs', '@angular/forms': 'npm:@angular/forms/fesm2022/forms.mjs', 'jszip': 'npm:jszip/dist/jszip.min.js', 'typescript': 'npm:typescript/lib/typescript.js', 'ts': './plugin.js', 'tslib':'npm:tslib/tslib.js', 'css': 'npm:systemjs-plugin-css/css.js', 'plugin-babel': 'npm:systemjs-plugin-babel/plugin-babel.js', 'systemjs-babel-build':'npm:systemjs-plugin-babel/systemjs-babel-browser.js', '@mescius/spread-sheets': 'npm:@mescius/spread-sheets/index.js', '@mescius/spread-sheets-tablesheet': 'npm:@mescius/spread-sheets-tablesheet/index.js', '@mescius/spread-sheets-angular': 'npm:@mescius/spread-sheets-angular/fesm2020/mescius-spread-sheets-angular.mjs', '@grapecity/jsob-test-dependency-package/react-components': 'npm:@grapecity/jsob-test-dependency-package/react-components/index.js' }, // packages tells the System loader how to load when no filename and/or no extension packages: { src: { defaultExtension: 'ts' }, rxjs: { defaultExtension: 'js' }, "node_modules": { defaultExtension: 'js' }, "node_modules/@angular": { defaultExtension: 'mjs' }, "@mescius/spread-sheets-angular": { defaultExtension: 'mjs' }, '@angular/core': { defaultExtension: 'mjs', main: 'core.mjs' } } }); })(this);