Search code examples
javascriptag-gridag-grid-ng2

Can we lazy load data for dropdown while doing inline edit?


I am working on inline-editing functionality with .

As per official documentation: ag-Grid Cell Editing, we can provide dropdown options values while providing column definition colDef itself.

colDef.cellEditor = 'selectCellEditor';
colDef.cellEditorParams = {
    values: ['English', 'Spanish', 'French', 'Portuguese', '(other)']
}

What to do when these values are to be fetched from server? i.e. Can we lazy load and then provide cellEditorParams values for the dropdown? (I haven't come across any)

Any solution or even direction would be appreciated.


Solution

  • You can create custom editor component having dropdown as template and make HTTP call to load the data for the dropdown.
    i.e., while creating ColDef for the column,

    let column: ColDef = {
            headerName: 'Lookup', field: 'FieldName', coldId: 'Id'
            cellEditorFramework: DropdownEditorComponent,
            cellEditorParams: {} // whatever data you want to have in editor component
    }
    

    In the editor component,

    import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { ICellEditorAngularComp } from 'ag-grid-angular';
    import * as _ from 'underscore';
    // import HttpService
    
    @Component({
        template: `
        <select [(ngModel)]="selectedValue" (change)="selectionChanged()" #dropdown>
            <option *ngFor="let item of items" [ngValue]="item">{{item.label}}</option>
        </select>
        `
    })
    

    Component definition:

    export class DropdownEditorComponent implements ICellEditorAngularComp, AfterViewInit {
    
        private params: any;
        private items: any[];
        private selectedValue: any;
        private selectControl: ElementRef;
    
        @ViewChild('dropdown') dropdown: ElementRef;
    
        constructor(private http: HttpService) {
            this.items = [];
        }        
        ngAfterViewInit() {
            this.selectControl = this.dropdown;
        }
    
        agInit(params: any): void {
            if(this.items.length == 0) {
                this.params = params;
                this.http.post(url, params)
                // this.http.get(url) // if the call is a GET
                    .subscribe(result => {
                        this.items = result;
                        this.selectedValue = _.find(this.items, item => item.label == params.value);
                    });
            }
        }
    
        getValue(): any {
            return this.selectedValue.label;
        }
        isPopup(): boolean {
            return false;
        }
        setValue(value: any): any {
            this.selectedValue = value;
        }
        selectionChanged(): void {
            // whatever you want to do
        }
    }