Josselin PEREZ
Josselin PEREZ

Reputation: 316

Angular - (click) event on a generated table cell

I've been trying to add a (click) event on a cell in a dynamically generated table.

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;
  };

When I do this, I get this error :

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

How could I add this event, provided I need to generate that table ?

Feel free to ask for more details if needed.

Upvotes: 4

Views: 18948

Answers (1)

Josselin PEREZ
Josselin PEREZ

Reputation: 316

Here is how I solved it:

Template :

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

Component :

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);
    }
  };

Upvotes: 8

Related Questions