Angular2: How to Pass Callback Functions to a Component

There are lots of situations where it’s useful to pass a function to an angular2 component, for instance, when our component is a dialog and we have to perform an specific task when it closes, or pass the action of one of its buttons, or even events like keypress, resize, mouseover, etc. If you’re reading this tutorial I’m sure you came across your own situation.

As an example I’m going to create a component with just a button, when clicked it will execute the callback function passed to the component, simple as that. Now let’s see the code:

@Component({
  selector: 'my-component',
  template: `
     <button type="button" (click)="callback()" >Callback Test</button>
  `
})
export class MyComponent { 
 
   @Input() callback: Function;
 
}

The first thing we have to do is to create a variable so we can assign the callback to it, in this example I’ve declared the variable callback and specified it to be a Function, I’ve also decorated it with @Input(), this will allow us to pass our function to this component. We can use this variable in the template as if it were a regular function, as you can see I’m binding it to the button click event like this: (click)="callback()".

Now let’s see how to pass our function to the component:

@Component({
  selector: 'my-app',
  template: `
  	<my-component  [callback]="showMessage"></my-component>
  `,
})
export class AppComponent { 
   showMessage(){
      alert('Callback Test');
   }
}

First, of course, we must have a function, in this case I’ve created the showMessage(), we can pass it by just adding [callback]="showMessage" to the component on the template, this binds the showMessage function to the callback property we saw on the previous component.

Now if you run the application you’ll see that the showMessage() is called when you click on the button.

Recommended for you

2 comments on “Angular2: How to Pass Callback Functions to a Component

  1. Bhushan
    @Component({
      selector: 'my-app',
      template: `
     
      `,
    })
    export class AppComponent { 
    name="Bhushan";
       showMessage(){
          alert('name = ' + this.name );
       }
    }

    in above code i did some modification, i added name variable on page load (i.e. name=”Bhushan”) and on click of button “showMessage” method will call. in that “this.name” gets “undefined”. can we help me to find out where i did mistake.

    P.S. i did same thing which you explain in above.

    1. delfre10

      Hi Bhusan,

      Try to do this at the constructor:

      this.showMessageFn = this.showMessage.bind(this);

      Then you can pass showMessageFn as input.

Leave a Reply to Bhushan Cancel reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>