Michail Michailidis Michail Michailidis - 1 year ago 679
TypeScript Question

Angular2 pass callback function to child component as @Input

AngularJS has the & parameters where you could pass a callback to a directive. Is it possible to pass a callback as an @Input for an Angular 2 Component (something like below)? If not what would be the closest thing to what AngularJS does?

selector: 'suggestion-menu',
providers: [SuggestService],
template: `
<div (mousedown)="suggestionWasClicked(suggestion)">
changeDetection: ChangeDetectionStrategy.Default
export class SuggestionMenuComponent {
@Input() callback: Function;

suggestionWasClicked(clickedEntry: SomeModel): void {
this.callback(clickedEntry, this.query);

<suggestion-menu callback="insertSuggestion">

Any help will be appreciated. Thanks!

Answer Source

Yes in fact it is, however you will want to make sure that it is scoped correctly. For this I've used a property to ensure that this means what I want it to.

  template: '<child [myCallback]="theBoundCallback"></child>',
  directives: [ChildComponent]
export class ParentComponent{
  public theBoundCallback: Function;

  public ngOnInit(){
    this.theBoundCallback = this.theCallback.bind(this);

  public theCallback(){

export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  public myCallback: Function;