当我点击子树时,如何从Angular自定义无限树视图中获取数组对象



我是一个Angular前端开发人员。我已经创建了一个Angular无限树视图。通常树视图显示正确,但当我点击子树,我想得到他的子树对象的子树对象。但问题是,当我点击子树时,它会在控制台中显示完整的父树数据。

请查看下面我当前的代码和功能:

树视图组件HTML:

<h2>{{ category!.Title }}</h2>
<ul *ngIf="category!.Children.length > 0">
<li style="margin-left: 20px;" *ngFor="let child of category!.Children" (click)="showVal(child)">
<b>></b> <app-tree-view-folder [category]="child"></app-tree-view-folder>
</li>
</ul>

树视图组件TS:

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
export interface Category {
Title: string;
Children: Category[];
}
@Component({
selector: 'app-tree-view-folder',
templateUrl: './tree-view-folder.component.html',
styleUrls: ['./tree-view-folder.component.css']
})
export class TreeViewFolderComponent implements OnInit {

@Input() category: Category | undefined;
@Output() clickOutside = new EventEmitter<any>();
constructor() { }
ngOnInit(): void {}
showVal(data:any){
this.clickOutside.emit(data);
}
}

我使用这个树的地方:

<app-tree-view-folder
[category]="category"
(clickOutside)="getCurrentData($event)">
</app-tree-view-folder>

And In TS文件:

category = {
Title: "Categorie Root",
Children: [
{
"Title": "Categorie A",
"Children": [ 
{
"Title": "Sub Categorie A",
"Children": []
}
]
},{
"Title": "Categorie B",
"Children": [
{
"Title": "Sub Categorie B",
"Children": [
{
"Title": "Sub Sub Categorie A",
"Children": [
{
"Title": "Sub Sub Categorie AA",
"Children": []
}
]
}
]
},
{
"Title": "Sub Categorie BB",
"Children": []
},
{
"Title": "Sub Categorie BBBB",
"Children": []
}
]
}
]
}
getCurrentData(data:any){
console.log(data);
}
我希望有人有解决这个问题的办法。由于

您只需要传递事件并使用event. stoppropagation。但是您需要将事件(clickOutside)添加到"内部threeview">

<ul *ngIf="category!.Children.length > 0">
<!--see how pass futhermore the "data" the "$event"-->
<li style="margin-left: 20px;" *ngFor="let child of category!.Children" 
(click)="showVal($event,child)">
<b>>{{child.Title}}</b> 
<!--see how you add the event (clickOutSide)-->
<app-tree-view-folder (clickOutside)="clickOutside.emit($event)" 
[category]="child" ></app-tree-view-folder>
</li>
</ul>

showVal变成了

showVal(event:Event,data:any){
event.stopPropagation();
this.clickOutside.emit(data);
}

stackblitz

最新更新