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

Time:10-04

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?

CodePudding user response:

Use arrow functions

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

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

  • Related