Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - (click) event on a generated table cell

Tags:

angular

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.

like image 917
Josselin PEREZ Avatar asked Mar 09 '23 20:03

Josselin PEREZ


1 Answers

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);
    }
  };
like image 154
Josselin PEREZ Avatar answered Mar 20 '23 11:03

Josselin PEREZ