首页 > 解决方案 > 需要在html中的列的每个单元格中添加复制按钮

问题描述

我正在尝试在我的角度应用程序中使用 ngx-clipboard 模块。

表中的数据来自服务,我jsonToTable()用来插入动态表。

组件.ts

generateOverrideCode(){

try {
    document.getElementById('tableGoesHere').innerHTML = this.jsonToTable(data, 'table table-sm table-dark');
  } 
catch (ex) {
  console.log('--generate override code', ex);  
}
}


capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

jsonToTable(json, classes){

var cols = Object.keys(json[0]);

var headerRow = '';
var bodyRows = '';

classes = classes || '';

cols.map((col)=>{
  headerRow += '<th>' + this.capitalizeFirstLetter(col) + '</th>';
});

json.map((row)=> {
  bodyRows += '<tr>';

  cols.map((colName)=> {
    if(colName != 'population')
    bodyRows += '<td>' + row[colName] + '</td>';
    else
    bodyRows += '<td id="colName+row">' + row[colName] + '<button></button>' + '</td>';  //I want to add a dynamic id to the button added to each cell of this row, so that i can use the id to target the text of that cell.
  });

  bodyRows += '</tr>';
});

return '<table class="' +
       classes +
       '"><thead><tr>' +
       headerRow +
       '</tr></thead><tbody>' +
       bodyRows +
       '</tbody></table>';
  }
 }
var data = [
{ country: 'China',         population: 1379510000 },
{ country: 'India',         population: 1330780000 },
{ country: 'United States', population:  324788000 },
{ country: 'Indonesia',     population:  260581000 },
{ country: 'Brazil',        population:  206855000 },
];

组件.html

<div class="row">
             <div class="col-sm-12">
                <button (click)="generateOverrideCode()">Generate</button>
            </div>
            </div>
            <div id="tableGoesHere"></div>

我想要实现的是在第三列中的每个单元格旁边添加一个复制按钮。 在此处输入图像描述

我还希望每个单元格都有一个唯一的 id,这样我就可以使用 ngx-clipboard 指令来定位它。以链接为例

https://maxisam.github.io/ngx-clipboard/

我也创建了一个 stackblitz 示例。 https://stackblitz.com/edit/angular-s5g1b5

请帮助我为每个单元格添加唯一 ID,然后我将继续添加 ngx-clipboard。(我在 stackblitz 中添加了评论,我尝试添加唯一 ID)

标签: javascripthtml

解决方案


推荐阅读