Angular 2中如何让包含内容的<td>单元格整体可点击?
Great question—adding click handlers to every inner element is definitely messy and unnecessary. Here are two clean, optimal approaches to make your entire <td> (including all its content) trigger the click event:
Approach 1: Use CSS to "Pass Through" Clicks to the <td>
This is the most reliable method, as it ensures no inner element intercepts the click. We'll use pointer-events: none on all child elements to make them ignore mouse events, so every click falls through to the parent <td>:
<td style="cursor: pointer;" (click)="onClickConfiguration($event, pr)"> <div *ngFor="let obj of parseConfiguration(pr)" style="white-space: normal; pointer-events: none;"> <label style="pointer-events: none;">{{obj.key}}</label>: {{obj.value}} </div> </td>
Why this works:
pointer-events: nonedisables all mouse interaction for the target elements (the<div>and<label>here). Any click on these elements will be "ignored" by them and instead trigger the click event on the nearest parent that accepts pointer events—your<td>.- The
cursor: pointeron the<td>ensures the hover effect is consistent across the entire cell, not just the text.
Approach 2: Leverage Default Event Bubbling (Simpler, Conditional)
If none of your inner elements have custom click handlers or call $event.stopPropagation(), the default browser behavior will already bubble clicks from child elements up to the <td>. That means your original code might already work!
When you click the <label> or text inside the <div>, the click event travels up the DOM tree to the <td>, triggering its (click) handler automatically.
When to use this:
- You're sure no inner elements are stopping event propagation (e.g., no
(click)="someFunc(); $event.stopPropagation()"anywhere in the child elements). - You don't want to add extra CSS rules.
If you find this approach isn't working, it's almost certainly because a child element is blocking the bubble—switch to Approach 1 to fix it.
内容的提问来源于stack exchange,提问作者ChrisGeo

