【问题标题】:How to display a div which is a value in my array of objects and embed it into a html page如何显示作为我的对象数组中的值的 div 并将其嵌入到 html 页面中
【发布时间】:2021-12-20 00:16:14
【问题描述】:

我有这个数组

        "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>"
            }
        ]

我正在使用 angular,我想访问具有视频的嵌入式 div。 我已经这样做了

<div *ngFor="let result of data.videos">
 <p> {{result.embed}} </p>
我在浏览器中的所有内容都是 div 标签,而不是嵌入视频。 有人可以帮忙吗

这是我的 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)})}}

我已经按照@BrunoElo 的建议解析了 JSON 数据,但即使在应用了之后,我仍然只得到标题而不是视频

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

【问题讨论】:

  • 你可以试试:

  • 我试过了,但在浏览器中没有得到任何结果
  • 我可能错了,但也许这些数据是 JSON 格式的,所以你需要先使用 JSON.parse(&lt;your array of data&gt;) 将其解析为对象,然后再使用 innerHTML 进行属性绑定
  • 这能回答你的问题吗? Angular HTML binding
  • 不,我在我的问题中添加了一些细节。

标签: javascript html json angular user-interface


【解决方案1】:

我很确定 2nd answer of this question 会解决您的问题,但我想这有点不同

注意:不要对响应进行字符串化或解析,它已经被 HttpClient 解析了

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

创建以下管道 - 并记住将其添加到模块 declarationsexports 字段(或将其添加到共享模块)

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

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

安全性:仅在您确实信任嵌入数据的来源时才使用此选项,否则您和您的应用程序将面临 XSS 攻击

【讨论】:

  • 这行得通,谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多