Call a function on click event in Angular 2

unknown picture unknown · Oct 24, 2016 · Viewed 394k times · Source

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>

//controller

app.controller('myCtrl', ['$scope', function($cope) {
    $scope.myFunc= {
        console.log("function called");
    };
}]);

Answer

sebaferreras picture sebaferreras · Oct 24, 2016

Component code:

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

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public items: Array<string>;

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

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

}

View:

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

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

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) { ... }