Angular2のクリックイベントで関数を呼び出す


95

コンポーネント(typescript)内で関数を宣言し、Angular 2のクリックイベントでそれを呼び出す方法は?以下は、Angular2コードが必要なAngular1の同じ機能のコードです。

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

//コントローラ

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

5
angular2これがAngular 1アプリの場合、なぜタグを付けたのですか?
ビートルジュース2016年

不十分な説明、構造的に間違った文、醜いコード。結果はすべて間違った理解になります。人々これはAngular1の質問です!
reyraa 2016年

1
私がコードで書いたものは何でも、angular2でも同じことをしたいです。
不明

古い投稿ですが、Angular2のドキュメントから「TourofHeros」を参照することをお勧めします。
ジェフ

Angular1またはAngular2ですか?指定されているはずです
SudhirKaushik18年

回答:


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と他のすべてのプッシュページには独自のものがありますが、ログオフしてログインページに移動した後、このメニューが予期せず表示されたため、クリックが消えた後、icantがこれを処理します。
sabre tabatabaee yazdi 2018

@sabertabatabaeeyazdi私がそれを見ることができるようにあなたの問題でStackblitzデモを作成していただけませんか?
sebaferreras 2018

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);
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.