我有一个带有分层数据的 JSON 文件:
[
{
"id": 0,
"label": "Gap Inc.",
"value": "Gap Inc",
"checked": false,
"children": [
{
"id": 0,
"label": "Banana Republic",
"value": "Banana Republic",
"checked": false
},
{
"id": 1,
"label": "Gap",
"value": "Gap ",
"checked": false
},
{
"id": 2,
"label": "Hill City",
"value": "Hill City",
"checked": false
},
{
"id": 3,
"label": "Old Navy",
"value": "Old Navy",
"checked": false
}
]
},
{
"id": 1,
"label": "Home Depot",
"value": "Home Depot",
"checked": false,
"children": []
},
{
"id": 2,
"label": "TJX",
"value": "TJX Companies",
"checked": false,
"children": [
{
"id": 0,
"label": "TJ Maxx",
"value": "TJ Maxx ",
"checked": false
},
{
"id": 1,
"label": "Marshalls",
"value": "Marshalls",
"checked": false
},
{
"id": 2,
"label": "Home Goods",
"value": "Home Goods",
"checked": false
}
]
}
]
我正在使用它来创建一组带有复选框的嵌套 HTML 列表:
<ul class="list-unstyled">
<li *ngFor="let parent of accountList; let q = index">
<div class="form-check">
<input id="parent-{{q}}"
class="form-check-input"
type="checkbox"
[(ngModel)]="parent.checked"
(click)="selectChildren(parent, $event)"
[indeterminate]="selectedChildren.length">
<label for="parent-item" class="form-check-label">
{{parent.label}}
</label>
</div>
<ul class="list-unstyled pl-4">
<li *ngFor="let child of parent.children; let i = index;">
<div class="form-check">
<input id="child-{{i}}"
class="form-check-input"
type="checkbox"
[(ngModel)]="child.checked"
(click)="selectChild(child, $event)">
<label for="child-{{i}}" class="form-check-label">
{{child.label}}
</label>
</div>
</li>
</ul>
</li>
</ul>
应该发生什么
如果单击父复选框,它会检查所有子复选框。如果您只单击一个子项,则其父项设置为不确定。
会发生什么
如果单击父复选框,它会检查所有子复选框。如果您只单击一个孩子,则所有父母都设置为不确定。
我想我在某个地方搞砸了。我想我已经将该属性映射到任何选定子indeterminate
项的长度(这里不仅仅是给定父项的子项。不知道如何解决这个问题......selectedChildren
这是打字稿:
selectedChildren = [];
selectChildren = function(data, event) {
const parentChecked = !data.checked;
data.children.forEach((child, key2) => {
child.checked = parentChecked;
});
};
selectChild = (data, event) => {
if (this.selectedChildren.indexOf(data.id) === -1) {
this.selectedChildren.push(data.id);
data.checked = true;
} else {
this.selectedChildren.splice(this.selectedChildren.indexOf(data.id), 1);
data.checked = false;
}
};