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

Interacting with Child Components in Angular2 There are lots of situations where we have to divide a component into several sub-components, resulting in a parent with N child components that somehow have to interact with the parent, like for example a menu component like this: In this case the menu-componen...
Using jQuery with Angular2 I know the idea of using jQuery with Angular2 may seen a little bit weird for lots of you, as we all know, Angular2 is responsible for managing everything related to our view components and DOM elements, it doesn't sound like a good idea to use another framework to do a job Angular can easily do. ...
Tutorial: How to redirect in Angular2 In this tutorial I'm going to give you a very simple example of how to navigate between components on an Angular2 application, but before we begin there are some configurations we have to do. We're going to use 2 components in this example: Component1 and Component2, to be able to redirect and na...
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 @...

3 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>