2017-07-31 96 views
0

我正在使用Angular-cli点击角度2捕获按钮属性

我有一个简单的数组,我循环并输出为按钮。

我加入循环索引作为一个属性上的按钮

如何获取按钮属性的点击时。

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

    @Component({ 
     selector: 'app-root', 
     templateUrl: './app.component.html', 
     styleUrls: ['./app.component.css'] 
    }) 

    export class AppComponent { 
     title = 'app works!'; 

     blocks: string[] = ['Red','Green','Blue','Yellow','White']; 

     constructor(){} 

     clickEvent($event){ 
     alert($event.target.attr.data-index); 
     } 

    } 




    // component.html 
    <div class="blocks"> 

     <div *ngFor="let block of blocks; let i=index"> 
     <button (click)="clickEvent($event)" [attr.data-index]="i">{{block}}</button> 
     </div> 

    </div> 

回答

2

有没有必要分配,然后从属性读取。您可以使用值直接

(click)="clickEvent(i)" 
1

您可以使用DOMStringMap访问通过dataset属性来获取数据的属性值:

clickEvent($event){ 
    alert($event.target.dataset.index); 
} 

或标准getAttribute方法:

clickEvent($event){ 
    alert($event.target.getAttribute('data-index'); 
} 

下面是从该文档报价:

在JavaScript中读取这些属性的值也很简单。您可以使用getAttribute()及其完整的HTML名称来读取 这些标准,但该标准定义了一种更简单的方法:您可以通过数据集属性读取DOMStringMap,您可以 。

要通过数据集对象获取数据属性,请在data-(注意破折号为 转换为camelCase)之后通过属性名称的一部分获取属性 。

1

如果您只是需要从数组当前项目,你可以将其发送到单击处理程序:

<button (click)="clickEvent($event, block)">{{block}}</button> 
clickEvent($event, block) { 
    alert(block); 
}