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

Angular2 Forms Tutorial: Creating Custom Validators Every now and then developers come across situations where existing validators are not suitable for their needs, if you are facing this situation your best option is to create a custom validatior, to illustrate how you can do that in angular2 I'm going to create a simple custom validator that will v...
Adding the Multiselect feature to an Angular2 Autocomplete Angular2 Multi Selection Autocomplete After I wrote the tutorial on how to create an angular2 autocomplete, lots of people have been asking me to add the multiselect feature to it, that's the reason why I decided to write this one. I'm going to continue from where I stopped, so make sure you fol...
Angular2: Uncaught (in promise): Error: Cannot match any routes: ” If you're specifying the routes on your project for the first time you may see the following error on the console when you run it: core.umd.js:3462 EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: ''ErrorHandler.handleError @ core.umd.js:3462next @ core.umd.js:6924schedulerFn @...
Angular2 Tutorial: Developing a Realtime Chat App Angular 2 Chat Application Hi guys, today we're going to make an awesome chat application with Angular2, NodeJS and Socket.io, this tutorial will involve quite a lot of things, and there are also lots of small details, so it will be a little bit longer than usual. To easily understand and make t...

5 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.

  2. Pratap A.K

    how to pass function which has parameters?

    my show methods looks like

    showMessage(message:string){
          alert('Callback Test');
       }

    when I did

     

    showMessage function getting invoked n number of times even before clicking the button.

    Please help me

Leave a 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>