[英]Call a function on click event in Angular 2
How to declare a function inside a component (typescript) and call it on a click event in Angular 2? 如何在组件(打字稿)中声明一个函数并在Angular 2中的click事件上调用它? Following is the code for the same functionality in Angular 1 for which I require Angular 2 code:
以下是我需要Angular 2代码的Angular 1中相同功能的代码:
<button ng-click="myFunc()"></button>
//controller //控制器
app.controller('myCtrl', ['$scope', function($cope) {
$scope.myFunc= {
console.log("function called");
};
}]);
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). 如您在代码中所看到的,我在声明这样的单击处理程序
(click)="open($event, item)"
,并将事件和项目(在*ngFor
声明)都发送到open()
方法(在组件代码中声明)。
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) { ... }
如果您只想显示项目,而无需从事件中获取信息,则可以执行
(click)="open(item)"
并修改open
方法,例如public open(item) { ... }
Exact transfer to Angular2+ is as below: 到Angular2 +的确切传输如下:
<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");
}
}
https://angular.io/guide/user-input-有一个简单的示例。
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! 控制器代码中的行显示
$scope.myFunc={
应该是$scope.myFunc = function() {
function()
部分很重要,它是一个函数!
The updated controller code would be 更新后的控制器代码为
app.controller('myCtrl',['$scope',function($cope){
$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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.