M. Akar
M. Akar

Reputation: 1865

How to obtain component instance in a function that is passed in as parameter?

I am using angular-resizable-element and the view expects a validateResize function to be passed in. My current code looks like following:

<div mwlResizable
     [enableGhostResize]="true"
     [validateResize]="validate"
     <!-- Other stuff -->
</div>

And the component:

@Component({
  // Stuff
})
export class TdeComponent {

  // Other code

  validate(event: ResizeEvent): boolean {

    if (event.rectangle.width < 50 ||  event.rectangle.height < 50)
      return false;

    // I need the component instance here.
    // However, `this` keyword refers to the caller, not to the component

    return true;
  }
}

Validate is passed in as a parameter. When it is called, this doesn't reference my component, it references the caller class. However, I need component variables inside this method. How can I access component reference inside validate method?

Upvotes: 1

Views: 205

Answers (1)

Alexy
Alexy

Reputation: 359

Use arrow functions

validate = (event: RedizeEvent) => {
    // code
}

Or bind context [validateResize]="validate.bind(this)"

Upvotes: 1

Related Questions