代码之家  ›  专栏  ›  技术社区  ›  Ankit Chaudhary

Angular 9:[innerHTML]如果不清理值,即使是纯字符串,也无法工作

  •  0
  • Ankit Chaudhary  · 技术社区  · 4 年前

    我有两个单空间的角9应用程序。

    以下代码在其中一个应用程序的浏览器文档上不打印文本,

    组件:

    myText = "some text"
    

    模板:

    <p [innerHtml]="myText"><p>
    

    如果我在段落中写了什么,即使没有打印出来:

    <p [innerHtml]="myText">Test<p>         // Test is also not getting printed
    

    然而,如果我 消毒 这个 myText 值它工作得很好。

    组件:

    // sanitizer is injected DomSanitizer service
    myText  = this.sanitizer.bypassSecurityTrustHtml("some text");
    

    模板:

    <p[innerHtml]=“myText”>&<p>
    

    但在我的另一个应用程序中,它运行良好。

    有人遇到过类似的问题吗?是否有任何应用程序配置或其他东西使innerHTML必须进行净化?

    0 回复  |  直到 4 年前
        1
  •  1
  •   mwilson    4 年前

    innterHTML 将清除该元素中发现的任何HTML(确切地说 内部html ). 如果你想在模板中添加额外的HTML,你必须在一个单独的元素中完成:

    <p [innerHtml]="myText"><p>
    <p>some more text</p>
    

    您可能会探索的另一件事是在TypeScript中创建附加值,并将其附加到在 [innerHTML] 结合。这将为您提供一种坚持使用一个元素的方法,而不必附加另一个元素。

    基本上,这与使用类似的东西非常相似 document.write . document.write 清除HTML并插入您传入的任何内容 innerHTML

    正在发生的事情的基本示例。请注意,当以下情况发生时,“占位符文本”将被完全清除 innerHTML 已设置。

    const exampleDiv = document.getElementById('example');
    exampleDiv.innerHTML = 'This is some text';
    <div id="example">Place holder text</div>

    以下是您的选择:

    const exampleDiv = document.getElementById('example1');
    const someTextIWantAppended = 'Some appended text';
    
    exampleDiv.innerHTML = `Some Inner HTML I want. ${someTextIWantAppended}`;
    
    // OR
    
    const exampleDiv2 = document.getElementById('example2');
    
    exampleDiv2.innerHTML = `Some Inner HTML I want.`;
    <strong>Example 1</strong>
    <div id="example1"></div>
    
    <hr />
    
    <strong>Example 2</strong>
    <div id="example2"></div>
    <div>Some appended text</div>