-2

i have below DataGrid columns cellTemplate coded as :

ctAccount(cellElement, cellInfo) {
 $('<div>')
      .appendTo(cellElement)
      .text(cellInfo.data.Other)
      .css('cursor', 'pointer')
      .on('click', function(event) {
             this.dDetail["aaa"] = { store: AspNetData.createStore({
                                                  key: "ID",
                                                  loadParams: { id: cellInfo.data.GroupID },
                                                  loadUrl: this.Svr.urlSuspect + "Group" 
                                              })
                                      };
       ...                      
       ...          

the problem is 'this' (this.dDetail, this.Svr) is not access by the compiler, because 'this' is referring to 'this: HTMLElement', not refer to my angular project. Error message is

property 'xxx' does not exist on type 'HTMLElement'.

How can i code on this.dDetail and this.Svr ?

Wilson
  • 162
  • 1
  • 1
  • 11

2 Answers2

0

Store the this reference in a variable at the correct scope, then use that variable within the click handler function:

ctAccount(cellElement, cellInfo) {
  let _this = this;
  $('<div>')
    .appendTo(cellElement)
    .text(cellInfo.data.Other)
    .css('cursor', 'pointer')
    .on('click', function(event) {
      _this.dDetail["aaa"] = {
        store: AspNetData.createStore({
          key: "ID",
          loadParams: {
            id: cellInfo.data.GroupID
          },
          loadUrl: _this.Svr.urlSuspect + "Group"
        })
      };
    });
  });
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • i try 2 solution but compile no problem, run time error : ERROR TypeError: Cannot read property 'dDetail' of undefined – Wilson Jun 08 '20 at 13:55
  • In which case it sounds like you're expecting `this` to be an even higher scope than the `ctAccount()` function. Use the same approach as outlined in this answer, but just define `_this` in the right place for the code you've got. – Rory McCrossan Jun 08 '20 at 14:29
  • i try to add in beginning : export class xxxComponent implements OnInit { _this = this; but no effect ! now the error is : cannot find name '_this' – Wilson Jun 08 '20 at 15:07
  • You forgot the `var` (or `let` if you're supporting ES6) – Rory McCrossan Jun 08 '20 at 15:40
0

You can use ES6 arrow functions.

Like

ctAccount(cellElement, cellInfo) {

  .on('click', (event) => {
         this.dDetail["aaa"] = { store: AspNetData.createStore({
Kiran Shinde
  • 5,732
  • 4
  • 24
  • 41