简体   繁体   English

角度2 ElementRef nativeElement offsetWidth始终为0

[英]Angular 2 ElementRef nativeElement offsetWidth always 0

I need to get the width of an element that has a dynamic width, I can get the width with pure javascript but not Angular 2. 我需要获取具有动态宽度的元素的宽度,我可以使用纯JavaScript而不是Angular 2来获取宽度。

constructor(private element: ElementRef) {
// ....

getting the width 得到宽度

let width =  this.element.nativeElement.offsetWidth;

console.log('js offset width', document.getElementById('foobar').offsetWidth);
console.log('angular2 offset width', width);

This works fine: 这很好用:

document.getElementById('foobar').offsetWidth 

But not angular 2's width, it's always 0. So how can I get the offset width via Angular's ElementRef? 但是不是angular 2的宽度,它始终是0。那么如何通过Angular的ElementRef获取偏移宽度呢?

You are not associating the TemplateRef with any of the DOM element 您没有将TemplateRef与任何DOM元素相关联

@ViewChild('foo') foo: TemplateRef;

Have the attribute in HTML as HTML中的属性为

 <div #foo></div>

Now OnInit try to get the value it will be a non zero. 现在,OnInit尝试获取它将为非零的值。

LIVE DEMO 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM