如果你已经在使用Angular-Bootstrap,那么你可以轻松地使用手风琴模块。 如果你正在寻找一种扩展现有下拉菜单模块的方法,你可能不需要我的解决方案。 它可能比你预期的代码更多,但请注意,其结构基本上是树视图的实现,因此甚至可以自由地将其用于此目的。
--- 提前说明:
我将提出一个通用的想法,这个想法是从我最近实现的一棵树中得出的。 请注意,该代码将为您提供实现所需功能的良好思路。 复制粘贴应该可以工作,但不能保证。 如果您想深入了解它,无论如何都应该阅读整个代码。
---
为了使用我要提出的代码,您需要一些基本结构来指示您的导航结构。 一些简单的json
或ts对象应该可以胜任。 我认为一个类似于这样的结构:
structure = [
{
title: "foo",
link: "/foo",
children: [
{
title: "bar",
link: "/bar",
children: []
}
]
},
{
title: "baz",
link: "/baz",
children: []
}
];
你应该明白这个想法。这将为您提供一个易于更改和实现的基础结构,只需更改对象中的细节即可更改结构。将其放在您想要呈现导航的父组件中。您可以采用不同的方法,但我喜欢使用Angular的潜力并使代码变得非常通用。如果您是程序员,您会理解需要一个易于使用的界面,基本上可以自动完成所有操作。
要显示结构,您还需要TreeViewComponent,它可以具有以下标记:
<ul class="tree-root-list">
<app-tree-node *ngFor="let item of structure"
[current]="item">
</app-tree-node>
</ul>
正如您应该已经意识到的那样,为了显示下拉树形导航菜单,您需要另一个组件。这个组件是 TreeNodeComponent,应该具有以下(大致)标记:
<li class="node-item">
// this function will trigger the final action triggered when a node is selected
// if there are subnodes open the list, else link to the respective page, route, etc..
<p #title (click)="nodeSelected()">
<span class="icon-container">
<span>
//optional icon
</span>
</span>
<span class="node-title">
// optional text
{{title}}
</span>
</p>
<ul class="child-list"
*ngIf="hasChildElements()"
[collapse]="children_collapsed"
(collapsed)="collapsed($event)"
(expanded)="expanded($event)">
// thats the part the structure object comes in handy,
// since you don't need to add several node tags
// you'll just need to add or remove elements in the structure
// variable
<app-tree-node *ngFor="let child of current.children"
[current]="child">
</app-tree-node>
</ul>
</li>
这是TreeNodeComponent的基本代码,只需根据您的需要进行调整即可使其正常工作。这应该已经包含了您想要的一般功能。
@Component({
selector : 'app-tree-node',
templateUrl: './tree-node.component.html',
styleUrls : ['tree-node.component.scss']
})
export class TreeNodeComponent implements OnInit {
@Input() current: any;
@Input() is_root: boolean;
public children_collapsed = true;
@ViewChildren(TreeNodeComponent) child_nodes: QueryList<TreeNodeComponent>;
public nodeSelected(): void {
if (this.hasChildElements()) {
this.children_collapsed = !this.children_collapsed;
} else {
}
}
public hasChildElements(): boolean {
return this.current.hasOwnProperty("children");
}
public collapsed(event: any): void {
if (this.hasChildElements()) {
this.folder_icon.nativeElement.className = "glyphicon glyphicon-folder-close";
}
}
public expanded(event: any): void {
if (this.hasChildElements()) {
this.folder_icon.nativeElement.className = "glyphicon glyphicon-folder-open";
}
}
}
我不会给你样式表,因为这首先是完全过度的,其次CSS很奇怪,每个人都有不同的解决方案。我相信你会找到适当的方式来为组件添加样式。
同样,不能保证所提供的代码复制粘贴后能够正常工作。原始项目包含了大量不同的树形功能,您在使用中可能并不需要一些变量。
祝好运,使用愉快。