" CONTENTEDITABLE"当元素通过" [innerHTML]"添加时,属性不起作用。在Angular

时间:2018-01-28 14:08:24

标签: html angular dom attributes

我在Angular中遇到contenteditable属性的意外行为。我有一个HTML对象,存储为值:

public json_html = {
  "button1":"<p contenteditable='true'>first section</p>",
  "button2":"<p>second section</p>",
  "button3":"<p>third section</p>",
}

我应用这样的值(通过innerHTML):

<div [innerHTML]="selectedButton"></div>

contenteditable属性外,一切正常 - 它只是在HTML中错过了:

enter image description here

问题:

如何强制使用contenteditable属性(当元素通过[innerHTML]时)?有没有正确的方法可以做到这一点,或者可能有一个解决方法?

直播示例: https://stackblitz.com/edit/angular-9pyhg3-lnivvj?file=app%2Fbutton-overview-example.html

1 个答案:

答案 0 :(得分:1)

出于安全原因,该属性被剥离

如果您告诉Angular它应该将其视为安全,请使用DomSanitizer

  constructor(sanitizer: DomSanitizer) {
    this.json_html =  {
    "button1": sanitizer.bypassSecurityTrustHtml("<p contenteditable='true'>first section</p>"),
    "button2":"<p>second section</p>",
    "button3":"<p>third section</p>",
  }

StackBlitz example