Michail Michailidis Michail Michailidis - 2 months ago 94
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?

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

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


<suggestion-menu callback="insertSuggestion">
</suggestion-menu>


Any help will be appreciated. Thanks!

Answer

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.

@Component({
  ...
  template: '<child [myCallback]="theBoundCallback"></child>',
  directives: [ChildComponent]
})
export class ParentComponent{
  public theBoundCallback: Function;

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

  public theCallback(){
    ...
  }
}

@Component({...})
export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  @Input()
  public myCallback: Function; 
  ...
}
Comments