2017.3.22
2017.4.17

Youtubeの動画を表示する

AngularJSでは事前にホワイトリストにURLを登録しておくことで、Youtubeの動画が表示できるようになっていましたが、Angular2の場合、sanitizerクラスのbypassSecurityTrustResourceUrl()メソッドで表示するURLを変換しないといけません。

URLを変換していない場合、ブラウザのコンソールに以下のようなエラーが出力されます。

unsafe value used in a resource URL context

以下は、Pipeという仕組みを仕組みを利用して、フィルターを通してURLを変換する方法になります。

目次

  • ディレクトリ、ファイルの構成
  • フィルター
  • コンポーネント
  • モジュール
  • 参考リンク

ディレクトリ、ファイルの構成

今回、試してみたディレクトリ、ファイルの構成は以下の通りです。(フィルター用に作成またはコードを追加したファイルのみ表示)

project
├ node_modules
└ src
    └ app
        ├ app.module.ts
        ├ app.url-safe.pipe.ts
        └ example
            ├ example.component.html
            └ example.component.ts

フィルター

app.url-safe.pipe.ts


import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safe' })
export class UrlSafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) { }
  transform(url: string) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

コンポーネント

example.component.html


<iframe [src]='videoUrl | safe' frameborder="0" allowfullscreen></iframe>

example.component.ts


import { Component } from '@angular/core';

@Component({
  templateUrl: 'example.component.html'
})
export class ExampleComponent {
  videoUrl = "https://www.youtube.com/embed/~~~";
}

モジュール

app.module.ts


import { NgModule }    from '@angular/core';
import { UrlSafePipe } from './app.url-safe.pipe';

@NgModule({
  declarations: [
    UrlSafePipe,
  ],
})

参考リンク

Angular】関連記事