问题
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