" CONTENTEDITABLE"当通过“[innerHTML]”添加元素时,属性不起作用。在Angular中 [英] "contenteditable" attribute doesn't work when element added via "[innerHTML]" in Angular

查看:111
本文介绍了" CONTENTEDITABLE"当通过“[innerHTML]”添加元素时,属性不起作用。在Angular中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  public json_html = {
button1:< ; p contenteditable ='true'>第一部分< / p>,
button2:< p>第二部分< / p>,
button3:< p> ;第三部分< / p>,
}

(经由 innerHTML ):

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

一切正常,除了 contenteditable 属性 - 它是错过了HTML:





问题:如何强制 contenteditable 属性起作用(当元素变成 [innerHTML的] )?有没有适当的方法来做到这一点,或可能有一种解决方法?



实际例子 https://stackblitz.com/edit/angular-9pyhg3-lnivvj?file=app%2Fbutton-overview-example.html

解决方案

该属性因安全原因被剥离

如果您告诉Angular它应该把它看作是安全的,使用 DomSanitizer

 构造函数(sanitizer:DomSanitizer) {
this.json_html = {
button1:sanitizer.bypassSecurityTrustHtml(< p contenteditable ='true'>第一部分< / p>),
button2: < p>第二区段< / p>,
button3:< p>第三区段< / p>,
}

StackBlitz例如


I have met an unexpected behavior for me of contenteditable attribute in Angular. I have an object with HTML, stored as a value:

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

And I apply this values like this (via innerHTML):

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

Everything works fine except contenteditable attribute - it's just missed in HTML:

QUESTION:

How to force contenteditable attribute to work (when element becomes through [innerHTML])? Is there a proper way to do that or may be there is a workaround?

LIVE EXAMPLE: https://stackblitz.com/edit/angular-9pyhg3-lnivvj?file=app%2Fbutton-overview-example.html

解决方案

That attribute is stripped for security reasons

If you tell Angular that it should treat it as safe, use 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

这篇关于&QUOT; CONTENTEDITABLE&QUOT;当通过“[innerHTML]”添加元素时,属性不起作用。在Angular中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆