首页 > 解决方案 > 有没有办法在设置元素大小后避免使用计时器?

问题描述

这是我正在尝试做的一个简化示例...

在下面的代码片段中,我想将一个 div 元素设置为新的大小,然后显示该元素的大小。如果我不使用计时器,则显示旧尺寸而不是新尺寸。

有没有我可以挂钩而不是在这里使用计时器的承诺或回调?

非常感谢 - 乔恩

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div 
      style="background-color: bisque; height:250px; width: 350px; position:relative;"> 

      <div 
        #sizeableDiv
        style="background-color:cornflowerblue;" 
        [ngStyle]="{'height':divHeight, 'width':divWidth}">
      </div>

      <div style="position:absolute; left:10px; bottom:10px">
        <button (click)="setDivSizeNoTimer()">Set Size no Timer</button>
        <button (click)="setDivSizeWithTimer()">Get Size with Timer</button>
      </div>

    </div>
  `,
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  @ViewChild("sizeableDiv", null) sizeableDiv: ElementRef; 

  title = 'angular-dom-promise-q';
  divWidth:string = "100px"; 
  divHeight:string = "100px"; 

  // 
  // we want to set the div size and display the new div size 
  // 

  // this will display incorrect div grid size
  setDivSizeNoTimer() {
    this.divWidth = "200px";
    this.divHeight = "200px"; 
    this.getDivSize();
  }

  // this will display correct div size 
  // is there any way to do this without the timer? 
  setDivSizeWithTimer() {
    this.divWidth = "200px";
    this.divHeight = "200px"; 
    setTimeout(
      () => {
        this.getDivSize()
      }, 1 
    )
  }

  private getDivSize() {
    console.log('Div size: ', this.sizeableDiv.nativeElement.offsetWidth, this.sizeableDiv.nativeElement.offsetHeight);
  }

}

标签: angularpromisecallbacksettimeout

解决方案


设置元素大小后,可以调用ChangeDetectorRef.detectChanges同步更新视图:

constructor(private changeDetectorRef: ChangeDetectorRef) { }

setDivSizeNoTimer() {
  this.divWidth = "200px";
  this.divHeight = "200px"; 
  this.changeDetectorRef.detectChanges();
  this.getDivSize();
}

有关演示,请参阅此 stackblitz


推荐阅读