Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

javascript - 在Angular 2中的click事件上调用函数(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");
    };
}]);
  ask by unknown translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...