I can not access to the Typescript Class with "this" after ngClick

I'm trying to acces to my class after a (click) on the template in Angular2+, but when I write console.log(this) I am getting the DOM object.

Let me show you my code:

deleteClient(row: Client, event: any): void
{

  console.log(this);
  console.log(event);
  console.log(this.notificationService);

  this.notificationService.open(...);

}

/* Aditional columns for clients. */
addAditionalColumns(): SpeerdListAdditionalColumn[]{

  let addAditionalColumns = [{
      label: "Delete",
      icon: "far fa-trash-alt",
      onclick: this.deleteClient,
      textAlign: 'center'
  }];

  return addAditionalColumns;
}

This is my template; list.tpl. I do a NgFor with the return off addAditionalColumns().

<!-- Additional columns -->
<ng-container *ngFor="let additionalColumn of additionalColumns" [cdkColumnDef]="additionalColumn.label">
       <!-- Head columns -->
       <cdk-header-cell *cdkHeaderCellDef [ngStyle]="{'text-align': additionalColumn.textAlign}">
               {{additionalColumn.label}} 
       </cdk-header-cell>
       <!-- Body columns -->
       <cdk-cell *cdkCellDef="let row" [ngStyle]="{'text-align': additionalColumn.textAlign}"> 
              <i (click)="$event.stopPropagation(); additionalColumn.onclick(row, $event);" class="{{additionalColumn.icon}}"></i> 
       </cdk-cell>
</ng-container>

What I am getting with the console.log(this) in deleteClient function is:

 {label: "Borrar", icon: "far fa-trash-alt", onclick: ƒ, textAlign: "center"}

And I need the ComponentClass instance. How can I access to class instance?

Code: https://stackblitz.com/edit/angular-votuyc?embed=1&file=src/app/app.component.ts

Upvotes: 0

Views: 68

Answers (1)

tylerherzog
tylerherzog

Reputation: 344

You can use the shorthand arrow function to do this for defining your method. Something like:

deleteClient = (row: Client, event: any): void => { 
    //this now refers to the component instance
} 

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions for more on that operator

Upvotes: 1

Related Questions