可以使用setTimeout
将事件处理程序放入JavaScript任务队列中,以便在DOM更新后执行。以下是一个示例:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('myInput') myInput: ElementRef;
handleClick() {
setTimeout(() => {
const value = this.myInput.nativeElement.value;
console.log(value);
}, 0);
}
}
其中,@ViewChild
用于获取DOM元素的引用,handleClick
是点击事件的处理程序。在setTimeout
中,我们通过this.myInput.nativeElement.value
获取输入框的值,该代码位于任务队列中并在DOM更新后执行。