ngFor youtube links with Domsanitizer in Angular2

北慕城南 提交于 2020-01-15 03:16:09

问题


I have youtube links in my mock memory database and I want to *ngFor these videos from youtube.

   let videos: any[] =[
            {videoURL: "ZOd5LI4-PcM"},
            {videoURL: "d6xQTf8M51A"},
            {videoURL :"BIfvIdEJb0U"}

        ];

like this.

I used service to connect my component with the server and now in the html, I have let v of videos. And within the iframe tages.. I did

<iframe src=v.videoURL></iframe>

But since it's external source, they are telling me to use Domsanitzer but I am stuck at this part.

I don't know how to sanitize links that are supposed to be looping.

constructor( private sanitizer: DomSanitizer) {
    this.sanitizer.bypassSecurityTrustResourceUrl('')

<- I don't know what to add here.


回答1:


You can create pipe like:

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

And use it the following way:

<div *ngFor="let video of videos">
  <iframe [src]="('https://www.youtube.com/embed/' + video.videoURL) | safe"></iframe>
</div>

Plunker Example

See also

  • How to set iframe src in Angular 2 without causing `unsafe value` exception?


来源:https://stackoverflow.com/questions/42500324/ngfor-youtube-links-with-domsanitizer-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!