首先,它知道如何使用 .css 来制作它。我发现这种美纯 CSS 中的极简树视图 https://www.cssscript.com/minimalist-tree-view-pure-css/
好了,有了这个想法我们就可以使用 Angular 来生成一个“递归组件”了。但首先我们必须考虑到我们需要使用“属性选择器”来不生成组件的标签。别担心,它只是用作选择器
selector: '[recursive]'
所以,不要写一些像
<recursive></recursive>
我们可以使用一些像
<ul recursive></ul>
嗯,这个组件就像
<li *ngFor="let item of children">
{{item.label}}
<ul recursive *ngIf="item.children"
[children]="item.children"
[parent]="self"
[level]="level!=undefined?level+1:0">
</ul>
</li>
@Component({
selector: '[recursive]', //<--the the "selector"
templateUrl:'./hello.component.html'
})
export class HelloComponent {
@Input() level: number;
@Input() label: string;
@Input() children: any;
@Input() parent: any;
self=this;
}
好吧,我添加了属性“level”和“parent”,我在代码中没有使用它们,但如果我们的组件制作“更多”来显示树,那么它们可能会很有趣。
我们的 app.component.html 有点像
<ul class="tree" recursive [children]="data"></ul>
当心。我需要在 app.component 中使用 ViewEncapsulation.None 来传输 .css
确保我们给[孩子]自己的数据
哪里,例如
data = [{label: "Parent1", children: [
{ label: "Parent 1's only child" }
]},
{label:"Parent2"},
{label:"Parent3", children: [
{ label: "1st Child of 3" ,children:[
{label:"1st grandchild"},
{label:"2nd grandchild"}
]},
{ label: "2nd Child of 3" },
{ label: "3rd Child of 3" }
]
},
{
label: "Parent 4", children: [
{ label: "Parent 4's only child" }
]}]
你可以看到在这次堆栈闪电战 https://stackblitz.com/edit/angular-a8psdg?file=src%2Fapp%2Fapp.component.ts
Updated如果我们想要添加打开/关闭功能,很容易添加一个跨度并使用 [ngClass] 来处理三种情况:doc、打开和关闭,因此我们的 recursive.html 变为
<li *ngFor="let item of children">
<span [ngClass]="!item.children?
'doc':item.isOpen?'open':'close'"
(click)="item.isOpen=!item.isOpen"></span>
{{item.label}}
<ul recursive *ngIf="item.children && item.isOpen"
[children]="item.children"
[parent]="self"
[level]="level!=undefined?level+1:0">
</ul>
</li>
我使用了 .css 像
.doc,.open,.close
{
display:inline-block;
width:1rem;
height:1rem;
background-size: 1rem 1rem;
}
.doc
{
background-image:url('...');
}
.open
{
background-image:url('...');
}
.close
{
background-image:url('...');
}
The 更新了堆栈闪电战 https://stackblitz.com/edit/angular-eeqbls?file=src%2Fapp%2Ftree-view.component.html
更新2我不喜欢太多使用 ViewEncapsulation.None,所以我们可以做一个解决方法,我们的递归组件变得像
<ul class="tree" *ngIf="level==undefined">
<ng-container *ngTemplateOutlet="tree;context:{children:children}">
</ng-container>
</ul>
<ng-container *ngIf="level!=undefined">
<ng-container *ngTemplateOutlet="tree;context:{children:children}">
</ng-container>
</ng-container>
<ng-template #tree let-children="children">
<li *ngFor="let item of children">
<span [ngClass]="!item.children?'doc':item.isOpen?'open':'close'" (click)="item.isOpen=!item.isOpen"></span>{{item.label}}
<ul recursive *ngIf="item.children && item.isOpen"
[children]="item.children"
[parent]="self"
[level]="level!=undefined?level+1:0">
</ul>
</li>
</ng-template>
那是。第一个使用<ul class="tree">...</ul>
,其他的不加<ul>
再次,最后的堆栈闪电战 https://stackblitz.com/edit/angular-476x7s?file=src%2Fapp%2Ftree-view.component.html