我试图制作手风琴,所以当你点击一个关卡时,它会逐渐显示每个新关卡,如果有的话,但是现在它只是递归地显示所有关卡的等级我的手风琴。我知道有些软件包可以帮到你,但我想创建自己的软件包以便更好地理解Angular4。这就是我的手风琴现在显示的方式,但我希望能够点击进入每个级别。
菜单2
菜单3
我假设我需要用循环索引或类似的东西跟踪水平,但我不太确定如何。
list.ts
export class List {
title: string;
children: any;
}
app.component.ts
import { Component } from '@angular/core';
import { List } from './list';
const LIST: List[] = [
{
title: 'Menu 1',
children: []
},
{
title: 'Menu 2',
children: [{
title: 'Sub Menu 2',
children: [{
title: 'Sub Sub Menu 2',
children: [{
title: 'Sub Sub Menu 2, Sibling 1',
children: []
},
{
title: 'Sub Sub Sub Menu 2, Sibling 2',
children: []
}]
}]
}]
},
{
title: 'Menu 3',
children: []
}
];
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<ul>
<ng-template #recursiveList let-list>
<li *ngFor="let item of list; let index = index"
[class.selected]="item === selectedList"
(click)="onSelect(item)">
<span> {{item.title}} </span>
<ul *ngIf="item.children.length > 0">
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }"></ng-container>
</ul>
</li>
</ng-template>
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
</ul>
`
})
export class AppComponent {
title = 'Nested Accordion';
list = LIST;
selectedList: List;
onSelect(list: List): void {
this.selectedList = list;
}
}
答案 0 :(得分:1)
您可以添加&#34;隐藏&#34; List对象上的属性,用于确定列表的子项是否可见,并在单击列表项时在true / false值之间切换。
以下是基于您的代码的演示Plunker:
https://plnkr.co/edit/CIGAA5BmiKU4hCMsOaIB?p=preview
export class List {
title: string;
children: any;
hide :boolean
}
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { List } from './list';
const LIST: List[] = [
{
title: 'Menu 1',
hide : true,
children: [],
},
{
title: 'Menu 2',
hide : true,
children: [{
title: 'Sub Menu 2',
hide : true,
children: [{
title: 'Sub Sub Menu 2',
hide : true,
children: [{
title: 'Sub Sub Menu 2, Sibling 1',
hide : true,
children: []
},
{
title: 'Sub Sub Sub Menu 2, Sibling 2',
hide : true,
children: []
}]
}]
}]
},
{
title: 'Menu 3',
hide : true,
children: []
}
];
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<ul>
<ng-template #recursiveList let-list>
<li *ngFor="let item of list; let index = index">
<span (click)="onSelect(item)"> {{item.title}} </span>
<ul *ngIf="item.children.length > 0 && !item.hide">
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }"></ng-container>
</ul>
</li>
</ng-template>
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
</ul>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
title = 'Nested Accordion';
list = LIST;
selectedList: List;
onSelect(list: List): void {
list.hide = !list.hide;
this.selectedList = list;
}