1

我有一个像这样的组件:

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 路由,并且我有嵌套/子路由。我不知道这些信息是否有用。

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

4

3 回答 3

2

我遇到了类似的问题,通过设置读取参数解决

进口

import { ElementRef } from '@angular/core';

查看孩子

@ViewChild(MyComponent, { read: ElementRef }) myComponent : ElementRef 

利用

onClick(){
    console.log("directive width:", this.myComponent.nativeElement.offsetWidth)
}

检查 doc上的元属性

于 2018-04-01T08:31:44.270 回答
0

第一个问题是您无法在 ngOnInit 中使用视图 html。您必须实现 AfterViewInit 接口和使用方法:

  ngAfterViewInit() {
    // ...
  }

在这种方法中,您可以使用您的 html 组件,因为组件已呈现并存在。试试看,我希望它可能会有所帮助。

于 2017-10-09T07:17:16.827 回答
0

这是客户端开发中的常见痛点。通常建议实现 AfterViewInit 并将代码置于超时状态。但是我也遇到了这个问题,特别是你描述的那种行为。我建议利用 RxJs 并实现以下内容:

ngAfterViewInit(){ interval(300).pipe(take(2)).subscribe(() => { //your code here// }); }

这为让视图内容呈现提供了一个很好的延迟,并且还进行了第二次传递,避免使用低效的 AfterViewChecked hack 等。

于 2021-05-04T18:32:03.863 回答