Angular 9 one-way binding not working on HTML5 video
I have the following HTML5 snippet in home-component.html:
<div id="main-tv-cabinet"> <video id="tv" autoplay preload="auto" controls width="640" height="480" (ended)="onTvPreviewEnded()"> <source src="{{sermonForPreview}}" type="video/mp4"> Sorry, your browser doesn't support embedded videos. </video> </div>
My view model is as follows:
export class HomeComponent { private sermonIndexForPreview : number = 0; private sermonsForPreview : string[] = []; public sermonForPreview = ""; constructor() this.sermonsForPreview.push("assets/videos/previous-sermon-snippet-1.mp4"); this.sermonsForPreview.push("assets/videos/previous-sermon-snippet-2.mp4"); this.sermonForPreview= this.sermonsForPreview[0]; } } public onTvPreviewEnded(){ this.sermonIndexForPreview = (this.sermonIndexForPreview + 1) % 2; this.sermonForPreview = this.sermonsForPreview[this.sermonIndexForPreview]; this.restartVideoPlayer(); console.log(this.sermonForPreview); } private restartVideoPlayer() { var tvScreen: any = document.getElementById("tv"); // TO FIGURE: why is binding not working here? tvScreen.src = this.sermonForPreview; if (tvScreen.paused) tvScreen.play(); else tvScreen.pause(); } }
When the video ends playing the first one, I expect the second to play and when the second one is done, back to the first, etc. The loopback is happening but the video element is stuck with whatever video is first in the list unless I comment out the line
tvScreen.src = this.sermonForPreview;
I understand that one-way binding should reflect changes in the view model back to the view. I even tried two-way biding with the [()] syntax but that did not solve it. What did I miss?
Take a look at StackBlitz I’ve created.
https://stackblitz.com/edit/angular-ivy-ela9eq
- Your binding was not working as you tried to set
src
attribute to thevideo
tag, not thesource
tag. - You were combining Angular’s data binding and basic JavaScript (in your
restartVideoPlayer()
method). You should think in declarative way and use just the binding if you can.