我有一个像这样的组件:
import { Component, OnInit, OnChanges, ViewChild, ElementRef, Input, Output, ViewEncapsulation, EventEmitter, AfterViewInit } from '@angular/core';
import * as d3 from 'd3';
@Component({
selector: 'coefficient-histogram',
templateUrl: './coefficient-histogram.component.html',
styleUrls: ['./coefficient-histogram.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CoefficientHistogramComponent implements OnInit {
@ViewChild('coefficienthistogram') private chartContainer:ElementRef;
constructor() { }
ngOnInit() {
let element = this.chartContainer.nativeElement;
console.log(element.offsetWidth);
}
}
使用这样的模板:
<div class="coefficenthistogram" #coefficienthistogram style="width: 100%; height: 100%"></div>
当我第一次浏览到包含组件的页面(或刷新页面)时,控制台将 offsetWidth 记录为 504,这是正确的大小,因为包含该元素的封闭 div 就是该大小。但是,当我导航到另一个页面然后返回到这个页面时,它会报告一个不同的大小 (308),这与它所在的容器不匹配。此外,如果我导航到另一个页面,然后返回到这个页面,它会报告一个不同的大小 (126)。
页面本身不会改变——这个组件的容器不会改变大小。我已经在 Chrome 调试器中验证了这一点 - 无论我加载新页面还是从其他页面导航到它,封闭 div 的宽度都是 504。
什么会导致 offsetWidth 根据我导航到的其他页面以不同方式报告???
我在应用程序中使用原生 angular 4 路由,并且我有嵌套/子路由。我不知道这些信息是否有用。
非常感谢这里的任何帮助。