0

我正在处理一个问题,我需要获取元素容器的宽度和高度才能在内部正确呈现 svg。问题是 OffsetWidth 和 Height 总是 0,我不知道我错过了什么。

父组件:

<div nz-row [nzGutter]="16">
    <div nz-col nzSpan="24">
        <nz-card nzHoverable>
            <nz-range-picker [ngModel]="initialRange" (ngModelChange)="onChange($event)" nzShowTime nzFormat="MM/dd/yyyy HH:mm:ss"></nz-range-picker>
            <bar-chart [data]="data"></bar-chart>
        </nz-card>
    </div>
</div>

条形图组件:

<div #chart class="chart-container"></div>

条形图css:

.chart-container {
    display: block;
    position: relative;
    width: 100%;
    height: 100%;
    max-width: 100%;
    overflow: hidden;
}

.chart-svg {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 500px;
}

条形图打字稿:

@Component({
    selector: 'bar-chart',
    templateUrl: './bar-chart.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./bar-chart.component.scss']
})
export class BarChartComponent extends BaseChart implements OnInit {
   @ViewChild('chart')
    private chartContainer: ElementRef;
    @Input()
    public data: DataModel[];
    public margin = { top: 20, right: 20, bottom: 30, left: 40 };

    constructor() {
        super();
    }
    public ngOnInit() {
        if (!this.data) {
            return;
        }

        this.draw();
    }

    private draw(): void {
        d3.select('svg').remove();

        const element = this.chartContainer.nativeElement;
        const data = this.data;

        const svg = d3.select(element).append('svg')
            .attr('class', 'chart-svg')
            .attr('width', element.offsetWidth)
            .attr('height', element.offsetHeight);

        const contentWidth = element.offsetWidth - this.margin.left - this.margin.right;
        const contentHeight = element.offsetHeight - this.margin.top - this.margin.bottom;
    }
}

我正在使用 ng-zorro-antd 进行 angular 7 的 UI 设计。

4

0 回答 0