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"); }; }]);
Introduction to AngularJs onclickThe ng-click directive can be used with multiple HTML elements such as button, input, select, checkbox, etc. This provides the developer ability to define custom behavior whenever an element is clicked.
Events are handled in Angular using the following special syntax. Bind the target event name within parentheses on the left of an equal sign, and event handler method or statement on the right. Above, (click) binds the button click event and onShow() statement calls the onShow() method of a component.
The $event object often contains information the method needs, such as a user's name or an image URL. The target event determines the shape of the $event object. If the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target.
In HTML, we can use the onclick attribute and assign a JavaScript function to it. We can also use the JavaScript's addEventListener() method and pass a click event to it for greater flexibility.
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) { ... }
Exact transfer to Angular2+ is as below:
<button (click)="myFunc()"></button>
also in your component file:
import { Component, OnInit } from "@angular/core"; @Component({ templateUrl:"button.html" //this is the component which has the above button html }) export class App implements OnInit{ constructor(){} ngOnInit(){ } myFunc(){ console.log("function called"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With