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");
};
}]);
This question is related to
javascript
angular
typescript
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
app.controller('myCtrl',['$scope',function($cope){
$scope.myFunc = function() {
console.log("function called");
};
}]);
https://angular.io/guide/user-input - there's a simple example .
This worked for me: :)
<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
alert('PlanId:' + planId + ' ParticipantId:' + participantId);
}
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");
}
}
Source: Stackoverflow.com