Angular 2 - change videos src after clicking on div

Changing src is not enough for <video>, you need to reload it:

constructor(private elRef: ElementRef) { }   // To find elements inside component

cameraStream(chosenCamera: string) {
  this.cameraSrc = chosenCamera;
  const player = this.elRef.nativeElement.querySelector('video');
  player.load();
}

Or more generally, you can make your component watch the changes through the OnChanges contract:

cameraStream(chosenCamera: string) {
  this.cameraSrc = chosenCamera;
}

ngOnChanges(changes: SimpleChanges): void {
  if (changes.cameraSrc) {
    const player = this.elRef.nativeElement.querySelector('video');
    player.load();
  }
}

(Of course you don't need to lookup the player element every time if you can secure its unchanging value before, like in ngOnInit)


Seems like the src attribute of the <source> element doesn't like to be dynamic. Try changing your markup to be:

<source *ngIf="cameraSrc" src="{{cameraSrc}}" type="video/mp4">

That way the DOM element only gets created when there is indeed a value in cameraSrc.


Don't know why, but that way:

<video width="800" [src] = "cameraSrc" controls>
    Your browser does not support HTML5 video.
</video>

It is working.


In html template use video tag

<video #video id="video" width="100%" height="100%" controls></video>

<mat-icon (click)="playVideo(url)">
            play_arrow
          </mat-icon>

In Component

@ViewChild('video')

public video: ElementRef;

playVideo(url: string) {
    this.video.nativeElement.src = url;
    this.video.nativeElement.load();
    this.video.nativeElement.play();
  }

Tags:

Html

Angular