模型更改后Angular View不更新 [英] Angular View not updating after model changes
问题描述
我有一个简单的角度应用程序,可使用以下JavaScript Web音频对象播放音频
i have a simple angular application to play audio using JavaScript web Audio Object below is
app.component.ts
app.component.ts
export class AppComponent {
title = 'media player';
audio;
currentTime: number;
constructor() {
this.audio = new Audio();
this.audio.src = './Music/demo2.MP3';
this.audio.play();
this.currentTime = this.audio.currentTime;
}
}
和 app.component.ts
and app.component.ts
<h4>{{ currentTime }}</h4>
一切正常,但是随着模型的改变视图不会更新
everything works fine but the view isn't update as the model changes
推荐答案
Angular会更新浏览器事件的绑定,因为相同的Angular使用zonejs
修补了多个浏览器事件,并触发了detectChanges
方法来保持绑定同步.
Angular does update binding on browser events for the same Angular uses zonejs
which monkey patches several browser events, and it fires detectChanges
method to keep binding in a sync.
在这种情况下,Angular不会更新绑定,因为Audio
API事件不会通过zonejs进行猴子补丁.对于这种情况,您必须手动运行更改检测以手动更新绑定.您可以使用audio
API的ontimeupdate
事件处理程序.
In this case Angular doesn't update binding, since Audio
API event's doesn't monkey patch by zonejs. For such scenarios you have to run change detection manually to update bindings manually. You could use ontimeupdate
event handler of audio
API.
import { ChangeDetectorRef, Component } from '@angular/core';
export class AppComponent {
title = 'media player';
audio;
currentTime: number;
constructor(private cd: ChangeDetectorRef ) {
}
ngOnInit(){
this.audio = new Audio();
this.audio.src = './Music/demo2.MP3';
this.audio.play();
//this will make sure to update when time updates.
this.audio.ontimeupdate = (event) => {
this.currentTime = this.audio.currentTime;
this.cd.detectChanges();
}
}
}
这篇关于模型更改后Angular View不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!