将不同的Event方法绑定到按钮单击以获取按钮列表

时间:2018-11-13 16:23:31

标签: angular typescript

我正在使用Angular 4中的html按钮。

patientCallStatusList = [{
  id: "1",
  label: "CALL CONNECTED",
  event: "notConnected"
}, {
  id: "2",
  label: "CALL NOT CONNECTED",
  event: "notConnected"
}, {
  id: "3",
  label: "PATIENT CALL BACK",
  event: "notConnected"
}];
<button *ngFor="let item of patientCallStatusList" mat-raised-button class="patientstatusButton" (click)="onButonClick(item)">{{item.label}}</button>

我必须将事件绑定到按钮的单击动作,以便它将重定向到垂直方法。我该怎么办,请帮帮我。

3 个答案:

答案 0 :(得分:1)

如何将此方法添加到数组中的每个obj,然后将其传递给单击按钮的功能? 例如-

  patientCallStatusList = [{
  id: "1",
  label: "CALL CONNECTED",
  event: "notConnected",
  itemFunction: ()=>{console.log(id)
    }, {
  id: "2",
  label: "CALL NOT CONNECTED",
  event: "notConnected",
  itemFunction: ()=>{console.log(id)
  }, {
  id: "3",
  label: "PATIENT CALL BACK",
  event: "notConnected",
  itemFunction: ()=>{console.log(id)
  }]; 

     and at the button =>
     <button (click)="someFunction(item.itemFunction)"></button>

答案 1 :(得分:0)

在按钮上,您已经通过(click)="onButonClick(item)"

将整个项目作为参数传递

可以仅基于值进行切换,并避免更改arr.obj(伪);

onButtonClick = (item) => {

   switch(item.id) {
     case 1:
        function1(item);
        break;
     case 2:
     case 3:
     case 4:
        function2(item);
        break;
     default:
        somethingElse(item);  
   }

}

答案 2 :(得分:0)

如果我对您的理解正确无误,则将有帮助

import {
  Component
} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private patientCallStatusList = [{
    id: "1",
    label: "CALL CONNECTED",
    event: "notConnected",
    clickFunction: (id) => {
      console.log(id);
    }
  }, {
    id: "2",
    label: "CALL NOT CONNECTED",
    event: "notConnected",
    clickFunction: (id) => {
      console.log(id);
    }
  }, {
    id: "3",
    label: "PATIENT CALL BACK",
    event: "notConnected",
    clickFunction: (id) => {
      console.log(id);
    }
  }];
}
<button *ngFor="let item of patientCallStatusList" mat-raised-button class="patientstatusButton" (click)="item['clickFunction'](item.id)">{{item.label}}</button>

https://stackblitz.com/edit/angular-by81aj