问题
I'm trying to build a small audio player but can't seem to get nice change detection, for example for the audio track current time. For example, I have the track playing fine in my component and in my template file I have
{{ player.currentTime }}
But the time only seems to be updated when I perform other events such as clicking around or play/pause button for example. It doesn't intuitively update live as the track is playing. Seems like issue with change detection or something?
For working example, see ngx-admin-demo (https://akveo.com/ngx-admin/#/pages/iot-dashboard) and scroll down slightly to see the player. If you press play and stop moving mouse you will see what I mean, it doesn't update progress bar or time unless you are performing action.
回答1:
Try something like this in your component to encourage change detection every second without the user having to perform some event to spur a change detection (Angular2+ only performs change detection on XHR requests, events and setTimeout/setInterval):
@Component({
selector: 'my-player',
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: '/path/to/my-player.template.html'
})
class MyPlayer {
constructor(private ref: ChangeDetectorRef) {
setInterval(() => {
this.ref.markForCheck();
}, 1000);
}
}
来源:https://stackoverflow.com/questions/54030943/angular-change-detection-with-htmlaudioelement