2017-06-14 62 views
2

我一直試圖在動態生成的表格中的單元格上添加(單擊)事件。生成表格單元格上的角度 - (單擊)事件

HTMLtoAdd:any; 
    @Input() roles:string; 
    ngOnInit() { 
    let alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; 
    let table = document.createElement('table'); 
    for (let i=0;i<10;i++){ 
     let newRow = document.createElement('tr'); 
     for (let j=0;j<10;j++) { 
     let newCell = document.createElement('td'); 
     let cellId = alphabet[i]+j; 
     newCell.setAttribute("id",cellId); 
     newCell.setAttribute("(click)","alert(this.id)"); 
     newRow.appendChild(newCell); 
     } 
     table.appendChild(newRow); 
    } 
    this.HTMLtoAdd = table.outerHTML; 
    }; 

當我這樣做,我得到這個錯誤:

'setAttribute' on 'Element': '(click)' is not a valid attribute name. 

我怎麼能添加此事件,只要我需要生成表?

隨意問如果需要更多的細節。

+0

有一個在HTML非標準無'(點擊)'屬性。它是角度特定的屬性,用於角度編譯模板時,它將在DOM之後從DOM中移除 – yurzui

+0

而不是使用香草javascript添加表格,而應該使用angular的'ngFor'來創建表格單元格。然後'(click)'綁定也會起作用。 – schrej

回答

3

這是我如何解決它:

模板:

<table> 
    <tr *ngFor="let row of columns"> 
    <td *ngFor="let cell of rows" (click)="log(row+cell)"></td> 
    </tr> 
</table> 

組件:

columns:string[]=[]; 
    rows:number[]=[]; 
ngOnInit() { 
    let gridSize = 10; 
    for (let i=0; i<gridSize;i++){ 
     this.columns.push(String.fromCharCode(65+i)); 
    }; 
    for (let i=0; i<gridSize;i++){ 
     this.rows.push(i); 
    } 
    };