4
votes

Does anyone know how to call service from ValueFormatter of ag-grid in Angular2+?

Example:

I have injected a service called someService in the constructor and would like to call the service from the ValueFormatter. What should i do to achieve that?

constructor(private service: SomeService) { }

this.columnDefs.push(
        {
            headerName: 'Date',
            width: 150,
            field: 'incidentDate',
            valueFormatter(params) {
                return this.service.doSomething(params.value);
            }
        });

At the moment, it doesn't recognise the service from the valueFormatter.

Thanks in advance

2
return this.service.doSomething(params.value); it means that you use this as a reference to the ag-grid component, it is not a reference to your hosted component. Therefore, you need to encapculate logic with a new private function inside your component and there you should use this to reference your hosted component and its injected service. - hastrb

2 Answers

12
votes

I have found a solution to my problem. I simply need to do the following:

 this.columnDefs.push(
    {
        headerName: 'Date',
        width: 150,
        field: 'incidentDate',
        valueFormatter: this.anotherFunction.bind(this)
    });

anotherFunction(params): string {
    return this.service.doSomething(params.value);
}
0
votes

You missed the reference of someService instance created from the constructor. Which can be fixed by having this keyword. Try the code below

valueFormatter(params) {
   return this.service.doSomething(params.value);
}