How to Embed a YouTube video in Angular?

YouTube videos are embedded as iframe. One embed code look like this,

<iframe width="560" height="315" src="https://www.youtube.com/embed/1ozGKlOzEVc" frameborder="0" allowfullscreen></iframe>

To make the YouTube Video work with Angular 2+, you have to sanitize the URL first.

import DomSanitizer to use it. So pass the videoURL as https://www.youtube.com/watch?v=1ozGKlOzEVc.

import { DomSanitizer } from '@angular/platform-browser';

Then add it to your constructor

constructor(videoURL: string, private _sanitizer: DomSanitizer){
   this.safeURL = this._sanitizer.bypassSecurityTrustResourceUrl(videoURL);
}

Then bind the value safeUrl to iframe.

<iframe [src]='safeURL' frameborder="0" allowfullscreen></iframe>

I don't know where exactly do you want to embed video but you can put somewhere in your HTML:

<iframe width="420" height="315" [src]="'https://www.youtube.com/embed/' + v.videoCode"></iframe>

There is now an Angular YouTube Player component

To understand the API you need to read the source. It has various inputs, outputs and functions. For example:

example.component.html

<youtube-player
  #player
  [videoId]="videoId"
  (ready)="onReady($event)"
  (stateChange)="onStateChange($event)"
></youtube-player>

example.component.ts

import { Component, Input, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'example'
  templateUrl: './example.component.html'
})
class YoutubePlayerExample implements OnInit {
  @ViewChild('player') player: any;
  videoId: string;

  @Input()
  set id(id: string) {
    this.videoId = id;
  }

  ngOnInit() {
    const tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    document.body.appendChild(tag);
  }

  // Autoplay
  onReady() {
    this.player.mute();         
    this.player.playVideo();    
  }

  // Loop
  onStateChange(event) {
    if (event.data === 0) {
      this.player.playVideo();  
    }
  }
}

example-module.ts

import { NgModule } from '@angular/core';
import { YouTubePlayerModule } from '@angular/youtube-player';

@NgModule({
  imports: [YouTubePlayerModule],
  declarations: [YoutubePlayerExample]
})
export class YoutubePlayerExampleModule {}

Tags:

Angular