【发布时间】: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