Angular pass callback function to child component as @Input similar to AngularJS way Angular pass callback function to child component as @Input similar to AngularJS way angularjs angularjs

Angular pass callback function to child component as @Input similar to AngularJS way


I think that is a bad solution. If you want to pass a Function into component with @Input(), @Output() decorator is what you are looking for.

export class SuggestionMenuComponent {    @Output() onSuggest: EventEmitter<any> = new EventEmitter();    suggestionWasClicked(clickedEntry: SomeModel): void {        this.onSuggest.emit([clickedEntry, this.query]);    }}<suggestion-menu (onSuggest)="insertSuggestion($event[0],$event[1])"></suggestion-menu>


UPDATE

This answer was submitted when Angular 2 was still in alpha and many of the features were unavailable / undocumented. While the below will still work, this method is now entirely outdated. I strongly recommend the accepted answer over the below.

Original 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;   ...}


In some cases, you might need business logic to be performed by a parent component. In the example below we have a child component that renders table row depending on the logic provided by the parent component:

@Component({  ...  template: '<table-component [getRowColor]="getColor"></table-component>',  directives: [TableComponent]})export class ParentComponent { // Pay attention on the way this function is declared. Using fat arrow (=>) declaration  // we can 'fixate' the context of `getColor` function // so that it is bound to ParentComponent as if .bind(this) was used. getColor = (row: Row) => {    return this.fancyColorService.getUserFavoriteColor(row); }}@Component({...})export class TableComponent{  // This will be bound to the ParentComponent.getColor.   // I found this way of declaration a bit safer and convenient than just raw Function declaration  @Input('getRowColor') getRowColor: (row: Row) => Color;  renderRow(){    ....    // Notice that `getRowColor` function holds parent's context because of a fat arrow function used in the parent    const color = this.getRowColor(row);    renderRow(row, color);  }}

So, I wanted to demonstrate 2 things here:

  1. Fat arrow (=>) functions instead of .bind(this) to hold the right context;
  2. Typesafe declaration of a callback function in the child component.