Angular 2选择器中[]的含义?PrimeNG源码相关技术疑问
Hey there! Let me clear up the confusion around those square brackets in the PrimeNG selector for you—they’re not just random syntax, they play a critical role in how Angular connects directives/components to your template elements.
What do the [] actually mean?
In Angular, selectors define how your directive or component attaches to DOM elements, and [pTreeRow] is an attribute selector. This means it targets any element that has the pTreeRow attribute, no matter what the element itself is (like a <tr>, <div>, or any other tag).
By contrast, pTreeRow (without brackets) is an element selector—it would only match standalone <p-tree-row> HTML tags, which isn’t how PrimeNG designed this directive to be used.
Why did removing the brackets trigger an error?
PrimeNG’s pTreeRow is a structural directive built to be applied to existing elements (most commonly table rows in the Tree component’s template, like <tr pTreeRow>). When you changed the selector to pTreeRow, Angular started searching for <p-tree-row> elements in your template—but your code is still using pTreeRow as an attribute on other elements. This mismatch causes Angular to throw an error, either because it can’t find the <p-tree-row> element it expects, or because it can’t resolve the pTreeRow attribute as a valid directive.
To give you context, here’s what a typical usage of pTreeRow looks like in a PrimeNG Tree template:
<tr pTreeRow [node]="currentNode"></tr>
The [pTreeRow] selector is exactly what lets Angular recognize that the pTreeRow directive should be applied to this <tr> element.
Quick recap
[pTreeRow]: Matches elements with thepTreeRowattribute (PrimeNG’s intended, functional usage)pTreeRow: Matches only<p-tree-row>elements (which doesn’t align with how this directive is built to work)
内容的提问来源于stack exchange,提问作者Alex

