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}` : '';
}
}