单击子树时如何从 Angular 自定义无限树视图获取数组对象

How to get Array object from Angular custom infinity tree view when I am clicking on the child tree

我是一名 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>

并且在 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)添加到“inner 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