在Angular 2中调用click事件上的函数 [英] Call a function on click event in Angular 2

查看:1096
本文介绍了在Angular 2中调用click事件上的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

//controller

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


推荐答案

组件代码:

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()方法(在组件代码中声明)。

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

如果您只是想显示该项目而您不需要从该事件中获取信息,您只需(点击)= open(item)并修改 open 方法,例如 public open(item){...}

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

这篇关于在Angular 2中调用click事件上的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆