Reputation: 213
I am trying to get table tr and second td values using parents('tr) and closest('tr') javascript methods and after selected dropdown.But not working i have searched in google nut no use.If anyone know please help to find the solutions.
app.component.html:
<table>
<thead>
<tr>
<td>Emp id</td>
<td>Roll id</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr>
<td>12345</td>
<td>18956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>18906</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>98956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>13956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
</tbody>
</table>
app.component.ts:
getTdValue(e){
let target = e.target.closest('tr');
if (target && target.id) {
let td = target.find('td:nth-child(2)');
if (td) {
console.log("Second td value is ="+ td.value )
}
}
}
https://stackblitz.com/edit/angular-peioe6?file=src/app/app.component.html
Upvotes: 0
Views: 1562
Reputation: 26150
First you need to have a second option
element inside your select
element in order to get any change events triggered.
<select (change)="getTdValue($event)">
<option></option>
<option>Get second td value of this row</option>
</select>
Then you can rewrite your getTdValue
method as follows:
getTdValue(mouseEvent: MouseEvent) {
let target = <HTMLSelectElement> mouseEvent.target;
let td = <HTMLTableCellElement> target.closest('tr').childNodes.item(1);
console.log("This row ID is " + td.innerHTML);
}
See following StackBlitz
UPDATE
When target.closest
doesn't work (Angular 6), it can be replaced by target.parentElement.parentElement
as follows:
getTdValue(mouseEvent: MouseEvent) {
let target = <HTMLSelectElement> mouseEvent.target;
let td = <HTMLTableCellElement> target.parentElement.parentElement.childNodes.item(1);
console.log("This row ID is " + td.innerHTML);
}
Upvotes: 1
Reputation: 66093
You have an if statement that evaluates the following condition: target && target.id
. Since none of your <tr>
element have an ID, the statement will evaluate to false, and none of the logic contained therein will be executed.
Since you are not using the ID for anything, you can simply remove it:
getTdValue(e){
let target = e.target.closest('tr');
if (target) {
let td = target.find('td:nth-child(2)');
if (td) {
console.log("Second td value is ="+ td.value )
}
}
}
Upvotes: 0