I am well aware of how you can style all your nodes at the same time but I need to add one styling if the node is a leaf (the node has children) but no parent and if the node has a parent but no children. Here is my code.
<p-tree [value]="nodes" layout="horizontal">
<ng-template let-node pTemplate="default">
<p>ADD CONTENT HERE</p>
</ng-template>
</p-tree>
Inspecting the styles once rendered shows that the class I need to change for each of the two conditions is ui-treenode
Adding classes to the styleClass
attribute of p-tree
makes it possible to style every node but I am not able to set anything conditionally here.
Adding the conditional style within the template does not function as I want since the pTemplate
renders the styles that I need to change.
I have read PrimeNG documentation several times and I haven't found any solution to this. Is there something build in or maybe a viable work around?
EDIT
Riscie suggested a solution but the class added in his demo is way deeper than the one I need to change. The class ui-treenode
is located at the top of the console window where the custom class leaf-style
is way deeper located in the bottom of the console window.
So why do I need to change that specific style? Because it adds some padding to the node - which I want to remove in certain cases and not all cases.
SECOND EDIT
This might not be the best way and I am not sure of its browser compatibility but it works as intended.
First of, add id to first div inside the template: id="{{node.data.id}}"
Second, loop through all nodes in ngAfterViewInit, fetch the node by id and its closest parent with the class ui-treenode
and the add the classes according to the conditions:
ngAfterViewInit(): void {
jQuery('.ui-tree-toggler').addClass('d-none');
jQuery('.ui-treenode-content').addClass('shadow');
jQuery('.ui-treenode-content').addClass('fp-tree-node');
this.nodes.forEach(node => {
this.setClasses(node);
});
}
setClasses(node: TreeNode) {
if(!node.children || node.children.length === 0) {
let thisNode = jQuery(`#${node.data.id}`);
let styleParent = thisNode.closest(".ui-treenode")
styleParent[0].classList.add("pl-0");
}
if(!node.data.parentId) {
let thisNode = jQuery(`#${node.data.id}`);
let styleParent = thisNode.closest(".ui-treenode")
styleParent[0].classList.add("pr-0");
}
if (node.children && node.children.length > 0) {
node.children.forEach(child => {
this.setClasses(child);
});
}
}