Angular 2 - ElementRef.nativeElement.offSetwidth 即使属性已更改也会返回相同的值

Jak*_*son 1 angularjs angular

我有一个 html 元素,如下所示:

   <h1 [style.font-size.em]="mysize" id="title-text" #titleText>{{ screenInfo.title }}</h1>
Run Code Online (Sandbox Code Playgroud)

其中 mysize 是控制 h1 标签字体大小的变量。h1 元素的宽度由内容的字体大小决定。

我得到了对 h1 标签的引用

   @ViewChild('titleText') titleTextElement;
Run Code Online (Sandbox Code Playgroud)

如果我运行以下代码,我会得到以下结果

   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.
Run Code Online (Sandbox Code Playgroud)

有人能解释为什么这不起作用吗?如果有人可以展示如何获取更新的 offSetwidth 值,我也将不胜感激。

Gün*_*uer 5

仅当运行更改检测时才会更新视图。

您可以手动调用更改检测,例如:

   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.
Run Code Online (Sandbox Code Playgroud)

它应该按预期工作。