简体   繁体   English

如何获取当前行 HTML 表格单元格元素?

[英]How to get current row HTML Table cell element?

I have a angular material table.我有一张angular的材质表。 If I click one row, i wanted to fetch the HTMLTableCellElement of the selected row .如果我单击一行,我想获取所选行的 HTMLTableCellElement。 I tried using viewChild but the problem is i am getting whole table html element.我尝试使用 viewChild 但问题是我正在获取整个表 html 元素。 Expected output预计 output HTMLTableCellElement 输出 Below is my code.下面是我的代码。 Please Help me to acheive this scenario !请帮助我实现这种情况! https://stackblitz.com/edit/angular-material-table-data-source-nym2vx?file=app/app.component.html https://stackblitz.com/edit/angular-material-table-data-source-nym2vx?file=app/app.component.html

In your example when you click on the a tag you can also send that tag to your function:在您的示例中,当您单击 a 标签时,您还可以将该标签发送到您的 function:

  <mat-cell *matCellDef="let element" id="{{ element.position }}">
    <a href="javascript:;" (click)="viewhtmlData($event.target)">{{
      element.name
    }}</a>
  </mat-cell>

Then, inside your function you can get the parent of that a tag which is the mat-cell containing it, like so:然后,在您的 function 中,您可以获得该标签的父级,该标签是包含它的 mat-cell,如下所示:

  viewhtmlData(aTag: HTMLElement) {
    console.log('Selected Row HtML data', aTag.parentElement);
  }

  <!-- CONSOLE OUTPUT -->
  <mat-cell _ngcontent-c69="" class="mat-cell cdk-column-name mat-column-name" role="gridcell" id="3">
    <a _ngcontent-c69="" href="javascript:;">Lithium</a>
  </mat-cell>

There are two changes you can make from the sample you have provided.您可以根据您提供的示例进行两项更改。

Change: 1 (in.html side) Pass event via the function: viewhtmlData()更改:1(in.html 端)通过 function 传递事件:viewhtmlData()

  <a href="javascript:;" (click)="viewhtmlData()">{{ element.name }}</a>

to

 <a href="javascript:;" (click)="viewhtmlData(element)">{{ element.name }}</a>

Change 2:(in.ts side) Pass the element through the function更改 2:(in.ts 端)通过 function 传递元素

// This function will show entire table contents
  viewhtmlData() {
    console.log('Selected Row HtML data',this.table);
  }

to

// The element data from  .html is passed through the function
  viewhtmlData($event) {
    console.log('Selected Row HtML data',$event);
    this.selectedElement =$event;
    var Row = document.getElementById($event.position)  as HTMLTableCellElement;    
    this.selectedCellHtml = Row;
   
    console.log('Selected Row HtML data',this.selectedCellHtml);
    
  }

For further reference, you can go through the below sample: https://stackblitz.com/edit/angular-material-table-data-source-gpybg5?file=app%2Fapp.component.ts如需进一步参考,您可以通过以下示例go:https://stackblitz.com/edit/angular-material-table-data-source-gpybg5?file=app%2Fapp.component.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM