Search code examples
javascripthtmlangularhtml5-videosrc

Embedding HTML5 <video> element in Angular, putting its source under [src] directive


I am trying to embed a sample video using the HTML5 video element in my Angular app. When I set the source attribute, using [src] directive, to a string (hard-coded) URL, the video successfully gets embedded, but when I set that same URL as, for example, _videoUrl field either as _videoUrl or this._videoUrl, the video gets crashed like it's disabled or something. One last thing, when I inspect the video element on the browser, I see its URL resolved and correctly placed in the src attribute, which is [src]="this._videoUrl" in the first place, anyway, still not working, so, anyone knows what's going on here?

NOTES:

  1. The video is a simple video hosted on AWS S3
  2. I am using Angular 9
  3. I am using the [src] in both cases, and never used the src attribute as is.

Code:

film.compontent.html

<div class="text-center col-2nd">
  <span style="display: block;">
    <video controls width="600px" height="300px">
      <source [src]="_videoUrl" type="video/mp4"/>
    </video>
  </span>
  <span style="display: block; font-size: 26px;">
    Official trailer
  </span>
</div>

film.component.ts

@Component({
  selector: 'app-film',
  templateUrl: './film.component.html',
  styleUrls: ['./film.component.css']
})
export class FilmComponent implements OnInit {
_videoUrl;
_videoStringUrl;

constructor(
    private route: ActivatedRoute,
    private server: ServerService,
    private sanitizer: DomSanitizer,
    private cartService: CartService
) { }

ngOnInit() {
    this._videoStringUrl = 'https://khadjiev-rk.s3.amazonaws.com/file_example_MP4_480_1_5MG.mp4';
    this._videoUrl = 
         this.sanitizer.bypassSecurityTrustUrl(this._videoStringUrl);
}
}

Solution

  • Demo use pipe for santizer to say binding is trustful

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
    
    @Pipe({
      name: 'safe'
    })
    export class SafePipe implements PipeTransform {
    
      constructor(protected sanitizer: DomSanitizer) {}
     
     public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
        switch (type) {
                case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
                case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
                case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
                case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
                case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
                default: throw new Error(`Invalid safe type specified: ${type}`);
            }
      }
    }
    

    your bind

    [src]="_videoUrl | safe : 'url'"