我创建了一个文件输入来打开视频。我想在 my_variable 存在的情况下显示该视频输入。 HTML 如下所示:
<input type="file" (change)="handleFileInput($event)" accept="video/mp4">
<div *ngIf="my_variable">
<video id="video" width="200" height="200" src="{{ my_variable.path }}">
</video>
</div>
只要用户选择视频,就会调用 (change) 事件。我的函数handleFileInput应该像这样更新my_variable:
handleFileInput(event: any) {
this.my_variable = event.target.files.item(0);
this.video = document.getElementById('video') as HTMLInputElement;
// do other stuff that requires this.video variable
}
我的问题是 this.video 变量为 null
。实际上,由于更改事件尚未完成,DOM 中的 ng if 条件不会更新 View ,然后,我的视频输入永远不会创建。因此,此时 this.video 为 null
。但我不知道如何解决这个问题。
我在 Stack Overflow 上没有找到任何内容,我尝试在执行 document.getElementById('video')
时设置超时。例如:
setTimeout(() => {
this.video = document.getElementById('video') as HTMLInputElement;
// do other stuff that requires this.video variable
}, 1000);
它确实有效,但我希望我能找到一个更清晰的解决方案。 请你帮助我好吗 ? 谢谢
最佳答案
不要使用 *ngIf
<div [style.display]="my_variable ? 'none' : 'block'">
<video ....>
</video>
</div>
关于javascript - 如何在更改事件完成之前更新 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59562237/