首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以角展开/折叠递归树菜单中的列表项

问以角展开/折叠递归树菜单中的列表项
EN

Stack Overflow用户
提问于 2018-02-28 21:17:55
回答 1查看 2.9K关注 0票数 1

如何实现嵌套列表在单击时展开?现在它刚刚打开第一层。

sidebar.component.html

代码语言:javascript
复制
   <ul>
    <ng-template #recursiveList let-list>
      <li *ngFor="let item of list" (click)="listClick($event, item)">
        {{item.name}}
        <ul *ngIf="item.folders?.length > 0" [ngClass]="{ 'subfolder': selectedItem == item }">
          <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.folders }"></ng-container>
        </ul>
      </li>
    </ng-template>
    <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
  </ul>

从sidebar.component.ts点击

代码语言:javascript
复制
listClick(event, newValue) {
    console.log(newValue);
    this.selectedItem = newValue;
  }

第一层的工作原理是应该的。我点击文件夹名,它就展开了。但是,当我单击下一级的list元素时,列表就会折叠,而不是进一步展开。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-01 07:19:34

我认为该事件正在向父元素冒泡,即当您单击一个子元素时,您也在单击父元素。添加event.stopPropagation()应该会阻止事件冒泡到父进程。也就是说。

代码语言:javascript
复制
listClick(event, newValue) {
    console.log(newValue);
    this.selectedItem = newValue;

    event.stopPropagation();
}

更新:我不确定您的数据是如何获取的,所以我不确定这是否是100%正确的。但是下面是一个工作示例,说明它应该如何工作(您确实需要event.stopPropagation();),我添加了&& item.showSubfolders,*ngIf,它在单击时被切换:

代码语言:javascript
复制
<ul>
    <ng-template #recursiveList let-list>
      <li *ngFor="let item of list" (click)="listClick($event, item)">
        {{item.name}}
        <ul *ngIf="item.folders?.length > 0 && item.showSubfolders" [ngClass]="{ 'subfolder': selectedItem == item }">
          <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.folders }"></ng-container>
        </ul>
      </li>
    </ng-template>
    <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
  </ul>

清单单击:

代码语言:javascript
复制
listClick(event, newValue) {
    console.log(newValue);
    this.selectedItem = newValue;
    newValue.showSubfolders = !newValue.showSubfolders
    event.stopPropagation()
  }

工作示例:https://stackblitz.com/edit/angular-emz37r

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49038715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档