如何在Angular2中嵌入YouTube视频?
我在YouTube上关注这个教程,它基本上是一张包含你喜欢的音乐的表格,但教程结束了。如何在Angular2中嵌入YouTube视频?
它使用Angular2,一切工作正常但是当绅士离开它,它只是显示在视频中使用此代码控制台的构造:
* Playlist.Component.Ts:
export class PlaylistComponent{
onSelect(vid:Video) {
console.log(JSON.stringify(vid)); } }
* Playlist.Component.html:
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>Title</td>
<td>Description</td>
</tr>
</thead>
<tbody>
<tr *ngFor="#v of videos" (click)="onSelect(v)">
<td>{{ v.id }}</td>
<td>{{ v.title }}</td>
<td>{{ v.desc }}</td>
</tr>
</tbody>
</table>
个* App.Component.Ts:
import {Component} from 'angular2/core';
import {Config} from './config.service';
import {Video} from './video';
import {PlaylistComponent} from './playlist.component';
@Component({
selector: 'my-app',
templateUrl: 'app/ts/app.component.html',
directives: [PlaylistComponent]
})
export class AppComponent {
mainHeading = Config.MAIN_HEADING;
videos:Array<Video>;
constructor() {
this.videos = [
new Video(1, "The 1975 - Somebody Else", "Bimd2nZirT4", "Calm."),
new Video(2, "Killswitch Engage - Holy Diver", "NR7dG_m3MsI", "Hell Yeah!")
]
}
}
*最后的Video.ts:
export class Video {
id: number;
title: string;
videoCode: string;
desc: string;
constructor(id: number, title: string, videoCode: string, desc: string){
this.id = id;
this.title = title;
this.videoCode = videoCode;
this.desc = desc;
}
}
我将如何得到它实际上是嵌入在浏览器中,一旦你在YouTube视频点击桌子?
YouTube视频嵌入的iframe中。一个嵌入代码看起来像这样,
<iframe width="560" height="315" src="https://www.youtube.com/embed/1KT2asqA1J8" frameborder="0" allowfullscreen></iframe>
要使YouTube视频与Angular 2一起工作,您必须首先清理URL。
导入DomSanitizer使用它。所以通过videoURL为 https://www.youtube.com/watch?v=1KT2asqA1J8
。
import { DomSanitizer } from '@angular/platform-browser';
然后把它添加到你的构造
constructor(videoURL: string, private _sanitizer: DomSanitizer){
this.safeURL = this._sanitizer.bypassSecurityTrustResourceUrl(videoURL);
}
则该值safeUrl
绑定到iframe中。
<iframe [src]='safeURL' frameborder="0" allowfullscreen></iframe>
我不知道你到底要嵌入视频,但你可以在你的HTML放的地方:
<iframe width="420" height="315" [src]="'https://www.youtube.com/embed/' + v.videoCode"></iframe>
谢谢,我会试试看(如果它是简单的东西我很抱歉,我还是新的这一切) –
顺便说一下,您使用的是一些角2测试版 - * ngFor =“#视频v “是旧的语法。新的一个是* ngFor =“让视频v” –
谢谢,只是想先掌握基础知识,我现在有一个Pluralsight帐户,将做最新的教程,但我开始了这一个,并希望看到它通过:) –
干杯伙计,现在排序! :) –