在Angular 2中的click事件上调用函数


95

如何在组件(打字稿)中声明一个函数并在Angular 2中的click事件上调用它?以下是我需要Angular 2代码的Angular 1中相同功能的代码:

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

//控制器

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

5
angular2如果这是一个Angular 1应用,为什么还要加上标签?
BeetleJuice

简短的描述,结构错误的句子,难看的代码。所有这些都会导致错误的理解。人们这是一个Angular1的问题!
Reyraa

1
无论我用什么代码编写,我都想在angular2中做同样的事情。
未知

旧帖子,但我建议您从角度2文档中查看“英雄之旅”。
杰夫

是Angular 1还是Angular 2?应该已经指定了它
Sudhir Kaushik

Answers:


120

组件代码:

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);
  }

}

视图:

<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>

正如您在代码中看到的那样,我在声明单击处理程序(click)="open($event, item)",并将事件和项目(在中声明*ngFor)都发送到open()方法(在组件代码中声明)。

如果您只想显示项目,而无需从事件中获取信息,则可以像这样(click)="open(item)"修改open方法public open(item) { ... }


注销后消失该菜单怎么办?我的databootstrapperpage使用这样的菜单以及其他所有推入页面都有自己的菜单,但是在注销和goto登录页面之后,此菜单意外出现,因此在单击消失后却可以处理。
saber tabatabaee yazdi '18

@sabertabatabaeeyazdi您可以为您的问题创建一个Stackblitz演示,以便我看看吗?
sebaferreras

57

Angular2 +的确切传输如下:

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

也在您的组件文件中:

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");
  }
}


3

控制器代码中的那行$scope.myFunc={应该是重要$scope.myFunc = function() {function()部分,以表明它是函数!

更新后的控制器代码为

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

1

这为我工作::)

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.