angular - 有没有办法在设置元素大小后避免使用计时器?
问题描述
这是我正在尝试做的一个简化示例...
在下面的代码片段中,我想将一个 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);
}
}
解决方案
设置元素大小后,可以调用ChangeDetectorRef.detectChanges
同步更新视图:
constructor(private changeDetectorRef: ChangeDetectorRef) { }
setDivSizeNoTimer() {
this.divWidth = "200px";
this.divHeight = "200px";
this.changeDetectorRef.detectChanges();
this.getDivSize();
}
有关演示,请参阅此 stackblitz。
推荐阅读
- php - 如何在提交事件之间持久化文件上传表单数据
- javascript - 如何在 php 表单帖子中使用由 javascript onclick 分配的输入值
- python-3.x - 熊猫数据框浮动索引不是自洽的
- reactjs - 如何将 const 变量从一个组件传递到另一个组件
- python - 如何在没有参考的情况下在管理站点成员中创建表
- azure - Azure 函数与 ASP.NET Core Worker 服务?
- ios - 如何在 Objective-C 中使用 swift Equatable 枚举
- sql - 如何延迟指定时间跨度的所有查询?
- r - 如何在 ggplot2 中创建具有 log10 比例和零值的箱线图
- javascript - 如何从 React-Redux 中的 reducer 中的状态更新对象数组中的单个元素的名称字段?