Search code examples
angulartypescriptangular2-formsag-grid

How to access Class Level Variable from onCellValueChanged of agGrid


I am new to Angular with Typescript. I want to access Class Level Variables inside onCellValueChanged event of agGrid. I am getting below error:-

Cannot read property 'updateDict' of undefined

My TypeScript Code as follows:-

import { Component, OnInit } from '@angular/core';
import { APICallService } from '../../.././PortalServices/webapicall.service';

@Component({
    selector: 'master-gender',
    templateUrl: 'app/PortalPages/MasterPages/GenderMaster/gender.component.html',
    providers: [APICallService],
})

export class GenderComponent implements OnInit {
    private updateDict = new Map();
    genderRowData: [];  

    constructor(private genderService: APICallService) {
    }

    ngOnInit() {
        this.genderService.getApiCall('getallgenders')
            .subscribe((rowData) => this.genderRowData = rowData,
                (error) => { alert(error) }
            );   
    }

    columnDefs = [
        {
            headerName: 'Gender Name', field: 'Name',          
            cellEditor: 'agLargeTextCellEditor',
            cellEditorParams: {
                maxLength: '100',
                cols: '20',
                rows: '2'
            },
            onCellValueChanged: this.genderCellValueChanged           
        },
    ]

    genderCellValueChanged(event: any) {
        let oldData = '';

        //Error coming from below line

        if (typeof (this.updateDict[event.data.GenderId + ',' + event.colDef.field]) != 'undefined')
            oldData = this.updateDict[event.data.GenderId + ',' + event.colDef.field].OldData;
        else
            oldData = event.oldValue;
        console.log(oldData);
    }
}
  1. How to resolve the issue?
  2. Is it possible to move "genderCellValueChanged" method to child component(separate .ts file)? If yes, can you please elaborate the steps?

Solution

  • You should use bind method to set the this context like this:

    onCellValueChanged: this.genderCellValueChanged.bind(this)
    

    Hope it helps.