Angular实现点击分类展示对应JSON子项的技术求助
实现点击分类展开子分类的交互效果
1. 组件逻辑修改(TypeScript)
在你的组件类中添加状态跟踪和切换逻辑:
import { Component } from '@angular/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent { // 原始分类数据 dataList = { "top wear": ["shirts", "t-shirts", "jackets"], "bottom wear": ["jeans", "chinos", "shorts"], "foot wear": ["shoes", "sandals", "slides"] }; // 记录当前选中的分类,初始无选中 selectedCategory: string | null = null; // 切换分类的展开/收起状态 toggleCategory(key: string) { this.selectedCategory = this.selectedCategory === key ? null : key; } }
2. 模板修改(HTML)
重构模板结构,将分类与子分类绑定,添加点击事件和条件显示:
<div class="cards"> <ul> <li *ngFor="let list of dataList | keyvalue" (click)="toggleCategory(list.key)" [class.active]="selectedCategory === list.key"> {{ list.key }} <!-- 子分类列表,仅当前分类选中时显示 --> <ul *ngIf="selectedCategory === list.key"> <li *ngFor="let item of list.value">{{ item }}</li> </ul> </li> </ul> </div>
3. 样式优化(CSS)
添加基础样式提升交互体验:
.cards ul { list-style-type: none; padding: 0; } .cards li { cursor: pointer; padding: 10px; margin: 5px 0; border-radius: 4px; transition: background-color 0.2s; } .cards li:hover { background-color: #f5f5f5; } .cards li.active { font-weight: bold; background-color: #e3f2fd; } .cards li ul { margin-top: 8px; margin-left: 20px; list-style-type: disc; } .cards li ul li { cursor: default; padding: 4px 0; background-color: transparent; }
效果说明
- 点击分类项可展开/收起对应子分类列表
- 选中的分类会高亮显示,鼠标悬停时有视觉反馈
- 子分类仅在对应分类被选中时展示
内容的提问来源于stack exchange,提问作者dev254
相关产品推荐
相关产品推荐

