首页 文章

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

提问于
浏览
45

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

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

//控制器

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

5 回答

  • 8

    组件代码:

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

  • 61

    准确转移到 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");
      }
    }
    
  • 34

    https://angular.io/guide/user-input - 有一个简单的例子 .

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

相关问题