Home > Mobile >  How to display a div which is a value in my array of objects and embed it into a html page
How to display a div which is a value in my array of objects and embed it into a html page

Time:11-08

I have this array

        "videos": [
            {
                "title": "0-1 \u00c1ngel Zald\u00edvar",
                "embed": "<div style='width:100%;height:0px;position:relative;padding-bottom:56.250%;'><iframe src='https:\/\/www.scorebat.com\/embed\/v\/61860cae4badd\/?utm_source=api&utm_medium=video&utm_campaign=v3' frameborder='0' width='100%' height='100%' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;'><\/iframe><\/div>"
            }
        ]

I'm using angular and i want to access the embeded div which has a video. I've done this

<div *ngFor="let result of data.videos">
 <p> {{result.embed}} </p>
All i'm in the browser is a div tag instead of an embeded video. Can someone help please

Here is my app.component.ts

export class AppComponent implements OnInit {stringfiedData:any;public data:any=[]constructor(private http: HttpClient) {}getData(){const url ='myApiUrl' this.http.get(url).subscribe((res)=>{this.stringifiedData = JSON.stringify(res);this.data = JSON.parse(this.stringifiedData);console.log(this.data)})}}

I have parsed the JSON data as suggested by @BrunoElo but still i get only the title but not the video even after applying the

 <p [innerHTML]="result.embed"></p>

CodePudding user response:

I'm pretty sure the 2nd answer of this question would solve your problem, but I guess it's a bit different

Note: don't stringify or parse the response, it will already have been parsed by the HttpClient

<div [innerHTML]="result.embed | safeHtml"></div>

Create the following pipe - and remember to add it to the module declarations and exports fields (or add it to a shared module)

@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe {
  constructor(private sanitizer:DomSanitizer){}

  transform(value: string) {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }
}

Security: only use this if you really do trust the source of the embed data, otherwise you leave yourself and your app open to XSS attacks

  • Related