在Angular 8中,设置ngStyle并读取offsetWidth可能会得到旧的值的问题可以通过使用ViewChild和ngAfterViewInit解决。下面是一个代码示例:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `
`,
styles: []
})
export class ExampleComponent implements AfterViewInit {
@ViewChild('myDiv', { static: false }) myDiv: ElementRef;
ngAfterViewInit() {
setTimeout(() => {
const offsetWidth = this.myDiv.nativeElement.offsetWidth;
console.log(offsetWidth); // 输出正确的值
}, 0);
}
}
在上面的例子中,我们使用ViewChild装饰器来获取模板中的div元素。然后,在ngAfterViewInit生命周期钩子中使用setTimeout来确保在视图初始化完成之后再获取offsetWidth的值。这样就可以得到正确的值。
请注意,在Angular 8中,ViewChild的第二个参数{ static: false }是必需的,以确保能够访问到元素。在Angular 9中,该参数的默认值将更改为true,所以上述代码示例在Angular 9中仍然有效。