79700080

Date: 2025-07-13 16:13:41
Score: 0.5
Natty:
Report link

When passing class methods as input properties in Angular, the function loses its this context. Here are muliple solutions:

Solution 1: Factory Function Pattern :

export class GaugesListComponent {
  constructor(private gs: GaugesService) {}

  // Factory that creates and returns the display function
  createDisplayFn(): (value: string) => string {
    return (value: string) => {
      const gauge = this.gs.getDirect(value);
      return gauge ? `${gauge.type} ${gauge.symbol}` : '';
    };
  }
}
<app-combobox
  [displayWith]="createDisplayFn()"
  ...>
</app-combobox>

Solution 2: Constructor Binding :

export class GaugesListComponent {
  constructor(private gs: GaugesService) {
    // Explicitly bind the method to the component instance
    this.displayWith = this.displayWith.bind(this);
  }

  displayWith(value: string): string {
    const gauge = this.gs.getDirect(value);
    return gauge ? `${gauge.type} ${gauge.symbol}` : '';
  }
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Starts with a question (0.5): When
  • Low reputation (1):
Posted by: ali abodaraa