角2-ElementRef.nativeElement.offSetwidth返回相同的值,即使属性已更改 [英] Angular 2 - ElementRef.nativeElement.offSetwidth returning same value even when property has changed
问题描述
我有一个看起来像这样的html元素:
I have a html element that looks like this:
<h1 [style.font-size.em]="mysize" id="title-text" #titleText>{{ screenInfo.title }}</h1>
mysize是一个变量,用于控制h1标签的字体大小.h1元素的宽度由内容的字体大小决定.
Where mysize is a variable that controls the font-size of the h1 tag. The h1 element's width is determined by the fontsize of the content.
我正在使用
@ViewChild('titleText') titleTextElement;
如果我运行以下代码,则会得到以下结果
If i run the following code i get the following results
console.log(this.titleTextElement.nativeElement.offsetWidth);
// returns 632px, which is the correct width.
this.mysize *= 0.9;
console.log(this.titleTextElement.nativeElement.offsetWidth);
// returns 632px, but the new width is 572px.
有人可以解释为什么这行不通吗?如果有人可以展示如何获取更新的offSetwidth值,我也将不胜感激.
Can anybody explain why this does not work? I would also appreciate if someone could show how I could get the updated offSetwidth value.
推荐答案
仅在运行更改检测时更新视图.
The view is only updated when change detection is run.
您可以手动调用更改检测,例如:
You can invoke change detection manually like:
constructor(private cdRef:ChangeDetectorRef) {}
...
console.log(this.titleTextElement.nativeElement.offsetWidth);
// returns 632px, which is the correct width.
this.mysize *= 0.9;
this.cdRef.detectChanges();
console.log(this.titleTextElement.nativeElement.offsetWidth);
// returns 632px, but the new width is 572px.
ant,它应能按预期工作.
ant it should work as expected.
这篇关于角2-ElementRef.nativeElement.offSetwidth返回相同的值,即使属性已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!