HTML 部分:
TS 部分:
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import * as d3 from 'd3';
@Component({
selector: 'app-tree',
templateUrl: './tree.component.html',
styleUrls: ['./tree.component.scss']
})
export class TreeComponent implements OnInit {
@ViewChild('svg_ele') svgEle: ElementRef;
constructor() { }
ngOnInit(): void {
const data = {
"name": "root",
"children": [
{ "name": "child1", "children": [] },
{ "name": "child2", "children": [
{ "name": "child3", "children": [] }
] },
{ "name": "child4", "children": [] },
{ "name": "child5", "children": [] },
{ "name": "child6", "children": [
{ "name": "child7", "children": [] },
{ "name": "child8", "children": [] },
{ "name": "child9", "children": [] }
] },
]
};
const svg = d3.select(this.svgEle.nativeElement);
const width = +svg.attr('width');
const height = +svg.attr('height');
const g = svg.append('g')
.attr('transform', `translate(20,20)`);
const tree = d3.tree()
.size([height-40, width-40]) // 高度和宽度不要超过svg的大小
.nodeSize([100,