Streaming YouTube Video in Angular Application

Angular and YouTube

Streaming YouTube Video in Angular Application

Streaming YouTube Video in Angular App

In this blog post we will going to learn how to integrate your YouTube video in your Angular application.

Pre-requisites :

  • Angular must be setup with minimum version 2

Setup an Angular project :

  • Use  Angular CLI (Command Line Interface) to create a new project, you can use any of the below command. Go the directory where you would like to create a project and then run below command.
    • ng new <project name> or
    • ng n <project name>

               For example :

    • ng new youtube-video
  • Now go into your project directory through terminal and run ‘ng serve’  command
    • cd youtube-video
    • ng serve -o

Above command will going to launch the application on http://localhost:4200/ and your project directory will going to look like

project-dir

After setting up the Angular project perform below steps:

            import { Component } from ‘@angular/core’;

             @Component({

                        selector: ‘app-root’,

                       templateUrl: ‘./app.component.html’,

                       styleUrls: [‘./app.component.css’]

                 })

                export class AppComponent {

                       public youtubeUrl = ‘https://www.youtube.com/watch?v=2dZT9GShJ3A&t=190s’;

                       public youtubeId = ‘2dZT9GShJ3A&t=190s’;

                       public embedUrl = ‘https://www.youtube.com/embed/’

                       videoUrl: string;

                       constructor() {

                              this.videoUrl =  this.embedUrl + this.youtubeId;

                            }

                    }

  • Copy below code in your app.component.html file which is available in your project directory to create the binding

             <iframe width=”250″ height=”150″ [src]=”videoUrl” allowfullscreen>

             </iframe>

    • Here we have used src attribute enclosed by square brackets ex: [src] this represents one way binding called as property binding in angular . Property binding is used to bind values to the DOM properties of the HTML elements.
    • <allowfullscreen> used here to enable fullscreen mode in youtube player.

DOM Sanitizer

  • DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing values to be safe to use in the different DOM contexts
  • When a value is inserted into a DOM from a template (via property, attribute, style, class binding, or interpolation), Angular treats all such values as untrusted by default. DOM Sanitizer comes as a rescue for us in such situation.

Use of DOM Sanitizer

  • The correct way to use DomSanitizer is by using a custom pipe and making sure we declare it as a pure pipe so Angular will cache our result and will not run it every time the change detection has fired.
  • Follow below steps to use DOM Sanitizer
    • Create PIPE using below command on Angular CLI (this will generate a file in directory)
      • ng generate pipe <pipe name> or ng g p <pipe name>

for example: ng generate  pipe safe-url, your project structure will be like below

app-dir
      • Import DomSanitizer from @angular/platform-browser in your safe-url.pipe.ts
        • import { DomSanitizer } from @angular/platform-browser;
      • Pass DomSanitizer in constructor
        • constructor(private sanitizer :DomSanitizer)
      • In transform method of pipe use bypassSecurityTrustResourceUrl method of DomSanitizer
        • transform(url) {

                                                 return this.sanitizer.bypassSecurityTrustResourceUrl(url)

                                           }

      • After following the above steps overall code in your safe-url.pipe.ts file should look like
        • import { Pipe, PipeTransform } from ‘@angular/core’

                                          import { DomSanitizer } from ‘@angular/platform-browser’

                                            @Pipe({

                                                   name: ‘safeUrl’

                                               })

                                        export class SafeUrlPipe implements PipeTransform {

                                        constructor(private sanitizer: DomSanitizer) {}

                                        transform(url) {

                                              return this.sanitizer.bypassSecurityTrustResourceUrl(url)

                                           }

                                  }

    • Update your app.component.html file with below code snippet

                       <iframe width=”250″ height=”150″ [src]=”videoUrl | safeUrl” frameborder=”0″ allowfullscreen> </iframe>

Share this post