2017-10-09 41 views
0

我有一个组件,象这样:角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路由,并且我有嵌套/子路由。我不知道这些信息是否有用。

这里的任何帮助非常感谢。

+2

尝试将代码移动到'ngAfterViewInit()' –

回答

0

第一个问题是,你不能在ngOnInit中使用你的view html。你必须实现AfterViewInit界面和使用方法:

ngAfterViewInit() { 
    // ... 
    } 

在这种方法中,你可以用你的HTML组件的工作,因为组件被渲染而存在。试试吧,我希望它可以帮到你。

+0

这会使问题更好,但不会完全消失。现在,当我从一个特定页面导航回来时,它工作正常。但是当我从其他页面导航时,大小会意外修改。 – jb44