我很清楚如何同时设置所有节点的样式,但是如果节点是叶子(节点有子节点)但没有父节点,并且节点有父节点但没有子节点,我需要添加一种样式。这是我的代码。
<p-tree [value]="nodes" layout="horizontal">
<ng-template let-node pTemplate="default">
<p>ADD CONTENT HERE</p>
</ng-template>
</p-tree>
检查渲染后的样式表明我需要为这两个条件中的每一个更改的类是ui-treenode
将类添加到styleClass
属性中p-tree
可以设置每个节点的样式,但我无法在此处有条件地设置任何内容。在模板中添加条件样式无法按我的意愿运行,因为pTemplate
渲染了我需要更改的样式。
我已经多次阅读 PrimeNG 文档,但没有找到任何解决方案。有什么内置的或可行的解决方法吗?
编辑
Riscie 提出了一个解决方案,但在他的演示中添加的课程比我需要更改的课程要深得多。该类ui-treenode
位于控制台窗口的顶部,其中自定义类leaf-style
位于控制台窗口底部的更深处。
那么为什么我需要改变那种特定的风格呢?因为它为节点添加了一些填充 - 我想在某些情况下而不是所有情况下删除它。
第二次编辑
这可能不是最好的方法,我不确定它的浏览器兼容性,但它可以按预期工作。
首先,在模板内的第一个 div 中添加 id:id="{{node.data.id}}"
其次,遍历 ngAfterViewInit 中的所有节点,通过 id 获取节点及其与类最近的父节点,并ui-treenode
根据条件添加类:
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);
});
}
}