angular - 子节点出现在每个父节点中
问题描述
子节点出现在每个父节点中。预期结果是子节点将出现在特定的父节点上。还有一个例子,一个子节点又多了一个子节点。
我们被建议不要为此使用库,因为之前我们使用 ngx 树视图,但是当我们使用它时,当我们使用其他搜索文本框时,我们会遇到过滤树视图内容的困难。
我做的第一件事是对父节点使用 FOR 循环。我使用 IF 条件来比较此父节点是否有子节点(在对象数组中)。如果满足 IF 条件,则此子节点将被推送到 THAT SPECIFIC PARENT NODE 的数组中,并返回将在 *ngIf 中使用的布尔变量。
this.service.Hierarchy() 传递的数据;是
[{文本:“Parent1”,值:1,孩子:数组(5),检查:假},
{文本:“Parent2”,值:1,孩子:数组(0),检查:假},
{文本:“Parent3”,值:1,孩子:数组(0),检查:假},
{文本:“Parent4”,值:1,孩子:数组(0),检查:假},]
在 .ts 文件
createTree() {
let hierarchy= this.service.Hierarchy(); //data passed
this.treeComponent = hierarchy;
for(let i=0; i<this.treeComponent.length; i++){
//Compare parent if has a children, Example 1 has a children
if(this.treeComponent[i].children.length != 0 ){
for(var children of this.treeComponent[i].children){
//use for ngIF
this.isChildrenAvailable = true;
this.child.push(children);
}
}
}}
在 .html 文件
<ul *ngFor="let item of treeComponent">
<input type="radio">
{{item.text}}
<div *ngIf = "isChildrenAvailable">
<ul *ngFor="let child of child" >
<input type="radio">
{{child.text}}
</ul>
</div>
</ul>
预期结果:
家长 1
孩子 1(父母 1 的孩子)
孩子 2(父母 1 的孩子)
` * Child Child 1(孩子 2 的孩子)
家长 2
- 家长 3
实际结果:
家长 1
孩子 1(父母 1 的孩子)
孩子 2(父母 1 的孩子)
家长 2
孩子 1(父母 1 的孩子)
孩子 2(父母 1 的孩子)
家长 3
孩子 1(父母 1 的孩子)
孩子 2(父母 1 的孩子)
解决方案
您可以简单地遍历模板中的子数组,如果您需要支持无限嵌套,您可以使用递归组件/模板
<ul>
<li *ngFor="let item of treeComponent">
<input type="radio">{{item.text}}
<div *ngIf="item.children.length">
<ul>
<li *ngFor="let child of item.children">
<input type="radio">{{child.text}}
</li>
</ul>
</div>
</li>
</ul>
推荐阅读
- scikit-learn - TypeError:预期的字符串或类似字节的对象 HashingVectorizer
- reactjs - 如何在反应中同步存储实例?
- maven - 当junit失败时将构建标记为不稳定
- javascript - 单击 JQuery 时未捕获的 ReferenceError
- python - 字符不存在时创建新列
- python - 在 Pandas 中使用 validate_email 包时出现 TypeError
- c# - 如何在 EF 中创建时间降序连接
- javascript - 在 Chrome 中裁剪 3D CSS 元素或在 Firefox 中根本没有 3D
- c# - Mindray-BS200 连接与 LIS 错误
- ios - 我可以为我的 iPhone 手动创建一个注册令牌以用于 Firebase 云消息传递吗?