javascript – Call a function on click event in Angular 2-ThrowExceptions

Exception or error:

How to declare a function inside a component (typescript) and call it on a click event in Angular 2?
Following is the code for the same functionality in Angular 1 for which I require Angular 2 code:

<button ng-click="myFunc()"></button>


app.controller('myCtrl', ['$scope', function($cope) {
    $scope.myFunc= {
        console.log("function called");
How to solve:

Component code:

import { Component } from "@angular/core";

export class HomePage {

  public items: Array<string>;

  constructor() {
    this.items = ["item1", "item2", "item3"]

  public open(event, item) {
    alert('Open ' + item);



  <ion-navbar primary>
      <span>My App</span>

    <ion-item *ngFor="let item of items" (click)="open($event, item)">
      {{ item }}

As you can see in the code, I’m declaring the click handler like this (click)="open($event, item)" and sending both the event and the item (declared in the *ngFor) to the open() method (declared in the component code).

If you just want to show the item and you don’t need to get info from the event, you can just do (click)="open(item)" and modify the open method like this public open(item) { ... }


Exact transfer to Angular2+ is as below:

<button (click)="myFunc()"></button>

also in your component file:

import { Component, OnInit } from "@angular/core";

  templateUrl:"button.html" //this is the component which has the above button html

export class App implements OnInit{



    console.log("function called");

### – there’s a simple example .


The line in your controller code, which reads $scope.myFunc={ should be $scope.myFunc = function() { the function() part is important to indicate, it is a function!

The updated controller code would be

    $scope.myFunc = function() {
    console.log("function called");


This worked for me: 🙂

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);

Leave a Reply

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