【问题标题】:Why don't the String values get displayed as HTML tags using innerHTML?为什么不使用 innerHTML 将字符串值显示为 HTML 标记?
【发布时间】:2019-02-11 18:40:04
【问题描述】:

我从我的数据库中获取字符串数据到我的变量中,我想通过 [innerHTML] 将它们显示为 HTML 标记,但它不起作用。 该变量显示在字符串而不是 HTML 标签上。

我尝试与 DomSanitizer 一起使用,但它不起作用:

    article:Article[];
    (article.articlesTitleHtml:SafeHtml;)

在函数中:

this.article.forEach(elementArticle => {
            elementArticle.articlesTitleHtml = this.sanitizer.bypassSecurityTrustHtml(elementArticle.articleTitle)
        });

在 HTML 页面中:

 <div *ngFor="let item of articles">
            <div id="{{item.articleId}}">
                <h2 class="chart" [innerHTML]="item.articlesTitleHtml"></h2>
            </div>

我的代码:

在类型脚本中:

    articles:Article[];

       ngOnInit() {
            this.apiArticle.getArticleList().subscribe(data=>{
                this.articles=data          
            })

在 HTML 页面中:

<div *ngFor="let item of articles">
        <div id="{{item.articleId}}">
        <h2 class="chart" [innerHTML]="item.articleTitle"></h2>
                </div>
            </div>

【问题讨论】:

  • 您的内容似乎不一致,[innerHTML]="item.articleTitle"[innerHTML]="articleTitleHtml"?

标签: html angular


【解决方案1】:

应该可以了,你可以check here...

如果您可以共享您正在处理的数据类型,它将更深入地了解应该调用的适当DomSanitizer 方法

在上面的示例中,我将 bypassSecurityTrustHtmlbypassSecurityTrustUrl 用于需要清理的 2 种不同类型的字符串

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2012-06-12
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多