Video html play with angular2+ directive using Universal SSR

I found the solution. The problem was that the code was called on the server-side because I was using Angular Universal. I don’t know why but seems like when HTMLVideoElement is in the server doesn’t have play(), load() and other methods. I think that this methods are implemented by the browser.

I solved checking where is the code by running an if statement in the directive.

import {Directive, ElementRef, Inject, OnInit, PLATFORM_ID} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';

@Directive({
  selector: '[appVideoAutoplayMuted]'
})
export class VideoAutoplayMutedDirective implements OnInit {

  constructor(public videoElement: ElementRef, @Inject(PLATFORM_ID) private platformId: any) {
  }

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) { // here is the check 
      const video: HTMLVideoElement = this.videoElement.nativeElement;
      video.muted = true;
      video.play();
    }
  }
}

Please, feels free to expand this answer so we can get a better knowleadge of what is going on.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top