【问题标题】:Is there a way to avoid using a timer after setting an element size?有没有办法在设置元素大小后避免使用计时器?
【发布时间】:2020-06-10 22:38:25
【问题描述】:

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

在下面的代码sn-p中,我想给一个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);
  }

}

【问题讨论】:

    标签: angular promise callback settimeout


    【解决方案1】:

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

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

    请参阅this stackblitz 以获取演示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      相关资源
      最近更新 更多