PrimeNG Tree组件点击事件异常:eventTarget.className.indexOf不是函数
eventTarget.className.indexOf is not a function Hey there, let's work through this frustrating issue with your PrimeNG Tree component. You mentioned you followed the official docs, other functions work fine, but clicking to expand nodes throws that TypeError—I've seen similar cases before, so here are the most likely fixes:
1. Check PrimeNG & Angular Version Compatibility
This error often pops up when there's a version mismatch between PrimeNG and your Angular setup. Older versions of PrimeNG's Tree component had a bug where they assumed eventTarget.className was a string, but in newer Angular environments, className returns a DOMTokenList instead.
- Head to the PrimeNG release notes and confirm you're using a version compatible with your Angular version.
- If you're on an older PrimeNG version, try upgrading to the latest stable patch (or a version explicitly marked compatible with your Angular setup).
2. Override Node Click Behavior Manually
If upgrading isn't an option right now, you can bypass the bug by handling the node click yourself and toggling the expanded state directly:
Step 1: Add a click handler in your component
import { TreeNodeClickEvent } from 'primeng/tree'; // ... onTreeNodeClick(event: TreeNodeClickEvent) { // Manually toggle the expanded state event.node.expanded = !event.node.expanded; // Add any additional logic you need here (like loading child nodes if lazy-loaded) }
Step 2: Update your template
Bind the nodeClick event to your handler in the Tree component:
<p-tree [value]="files" (nodeClick)="onTreeNodeClick($event)"></p-tree>
This skips the internal PrimeNG click logic that's throwing the error and gives you direct control over expanding/collapsing nodes.
3. Rule Out Global Event Interference
Sometimes third-party scripts or global event listeners on your page can modify the eventTarget or className property, causing this issue.
- Temporarily disable any non-essential global scripts (like analytics tools or custom event handlers) and test if the Tree works.
- Check if you have any custom directives that might be altering the DOM elements of the Tree nodes.
4. Verify Custom Node Templates (If Used)
If you're using a custom template for Tree nodes (with <ng-template pTemplate="default" let-node>), make sure you're not overriding the structure that PrimeNG expects.
- Ensure your template includes the necessary PrimeNG classes (like
p-tree-node-content) so the click event targets the correct element. - Avoid wrapping the node content in elements that might intercept the click event before it reaches PrimeNG's handlers.
Your backend code fetching the files JSON looks solid—this is definitely a frontend-side issue with event handling or versioning. Try the steps above, and the first two should resolve the problem in most cases!
内容的提问来源于stack exchange,提问作者user9364371

