以角度2

时间:2017-08-09 14:22:55

标签: angular

template
<button type="button"
        (click)="leaderBoard($event)"
        attr.leaders = "individual"
        [class.active]="individualLeaderboard">
   <label>INDIVIDUALS</label>
</button>
<button type="button"
        (click)="leaderBoard($event)"
         attr.leaders = "team"
         [class.active]="teamLeaderboard">
   <label>TEAMS</label>

.ts File

leaderBoard($event) {
    console.log($event.target.getAttribute('attr.leaders'))
 }

我只是在单击每个元素时尝试记录自定义属性的值。如果我只有一个按钮,它工作正常,但如果有多个按钮,则返回null。有人可以向我解释这个问题吗?

2 个答案:

答案 0 :(得分:1)

将您的HTML更改为:

<button type="button" (click)="leaderBoard($event)"
 leaders='individual' 
 [class.active]="individualLeaderboard">
 <label>INDIVIDUALS</label> 
</button> 

..并在你的ts:

leaderBoard($event){
console.log($event.currentTarget.getAttribute('leaders'));
 }

答案 1 :(得分:0)

你会用以下代码替换你的ts代码吗?

leaderBoard($event) {
    console.log($event.target.getAttribute('attr.leaders'));
}