Angular2 passing function as component input is not working

Issue

I’ve a component that takes function as input. I’ve passed this function from parent.

Though the function is called, the function is not able to access the dependencies of the instance on which this function is declared.

Here is the component

@Component({
  selector: 'custom-element',
  template: `
    {{val}}
  `
})
export class CustomElement {
  @Input() valFn: () => string;

  get val(): string {
    return this.valFn();
  }
}

Here is how the component is used

@Injectable()
export class CustomService {
  getVal(): string {
    return 'Hello world';
  }
}

@Component({
  selector: 'my-app',
  template: `
   <custom-element [valFn]="customVal"></custom-element>
  `,
})
export class App {
  constructor(private service: CustomService) {
  }
  customVal(): string {
    return this.service.getVal();
  }
}

When I run this app, I get an error in the console saying Cannot read property 'getVal' of undefined

Here is a plunker for the issue.

https://plnkr.co/edit/oQ229rXqOU9Zu1wQx18b?p=preview

Solution

You need to .bind(this) if you pass methods around:

<custom-element [valFn]="customVal.bind(this)"></custom-element>

or

export class App {
  constructor(private service: CustomService) {
  }
  customVal(): string {
    return this.service.getVal();
  }
  customValFn = this.customVal.bind(this);
}

with

<custom-element [valFn]="customValFn"></custom-element>

Answered By – Günter Zöchbauer

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.