我有一个组件,象这样:角4 viewchild nativeElement offsetWidth改变意外
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根据我导航到的其他页面以不同方式报告?
我在应用程序中使用本地角4路由,并且我有嵌套/子路由。我不知道这些信息是否有用。
这里的任何帮助非常感谢。
尝试将代码移动到'ngAfterViewInit()' –