ngFor youtube links with Domsanitizer in Angular2

2019-07-18 10:21发布

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条回答
做自己的国王
2楼-- · 2019-07-18 11:05

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

查看更多
登录 后发表回答