【问题标题】:ngModel is not working on <div> tag using contenteditable and have html as an inputngModel 无法使用 contenteditable 处理 <div> 标记并将 html 作为输入
【发布时间】:2017-11-03 10:20:48
【问题描述】:

我正在尝试绑定我的输入,即其中包含 html 内容的字符串。 app.component.ts 有“内容”变量

content : string = "<p>This is my editable data.</p><p>Two way binding is   not getting applied on it.</p>
public validateProfile(content){
console.log(content);
}

app.component.html 有以下代码

<div contentEditable="true" [innerHTML]="content" [(ngModel)]="content"></div>
  <button type="submit" class="btn btn-info" (click)="validateProfile(content)">Validate Profile</button> 

我可以编辑标签内的内容。由于我的输入是字符串格式的 html 数据,我无法将其绑定到输入标签。 有人可以建议如何在 div 或 span 上应用 contenteditable= true 的 2 路绑定。

【问题讨论】:

  • ng-model 不适用于 contenteditable。
  • ngModel 使用文本框 INPUT, TEXTAREA

标签: angular


【解决方案1】:

试试这样:

模板

<div contenteditable="true" [innerHTML]="content" (input)="contentNew=$event.target.textContent"></div>
<br/>
<button type="submit" class="btn btn-info" (click)="validateProfile(contentNew)">Validate Profile</button>

打字稿

  contentNew: string;
  content : string = "<p>This is my editable data.</p><p>Two way binding is   not getting applied on it.</p>";

  public validateProfile(content){
    this.contentNew = content;
    console.log(content);
  }

demo

【讨论】:

  • @Pallavi 你能关闭这个答案吗?
  • 我无法关闭它,因为我没有足够的声望点来关闭问题。
  • 作为 $event.target.textContent 给出的内容。例如:这将返回文本为“这是我的可编辑数据。没有应用双向绑定”,但是我们可以绑定整个 html 字符串,它可以返回为“

    这是我的可编辑数据。

    没有应用双向绑定。

    '?我尝试过将 innerHTML、outerHTML 作为 $event.target 的属性,但它们只返回内容。您对可以绑定整个 html 内容的任何属性有任何想法吗?
  • @Pallavi 尝试以下链接:- stackblitz.com/edit/angular-xtzzhu?file=app%2Fapp.component.ts 并检查 console.log 它将传递整个 html 元素
  • 现在整个内容都得到了反映。但是,在这种情况下,有 2 个 html 控件 - 1. 用于编辑 (div) 2. 用于显示 (p)。这两件事都必须发生在同一个控件上,无论是

    还是

    ,就像在您提供的以前的解决方案中发生的那样。
【解决方案2】:

要绑定一个值,请执行此操作

<div contenteditable=true (input)="content= $event.target.innerHTML; htmlContentChange($event.target.innerHTML)" (contentChange)="someFunction()"></div>

在你的组件中

export class myComponent {
    @Input() content;
    @Output() contentChange = new EventEmitter(); // for two way binding

   /*
   * update html on changes in content editable
   */
   htmlContentChange(value) {
      this.htmlChange.emit(value);
   }
}

【讨论】:

    【解决方案3】:

    我尝试了以下方法并且工作正常。 试试看

    <input type="text" [(ngModel)]="content"/>
    <div contentEditable="true" [(innerHTML)]="content" ></div>
    <button type="submit" class="btn btn-info" (click)="validateProfile(content)">Validate Profile</button> 
    

    【讨论】:

    • 这可行,但内容以 html 标签的形式出现。它必须显示为用户友好的文本。例如。它显示为

      Some Text。

      相反,它应该显示为:一些文本。此外,编辑必须只在 div 标签而不是 input 标签上进行。
    猜你喜欢
    • 1970-01-01
    • 2018-12-04
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多