【问题标题】:How to achieve 2 way data binding on a div's innerhtml property using ngModel如何使用 ngModel 在 div 的 innerhtml 属性上实现 2 路数据绑定
【发布时间】:2020-11-05 16:26:27
【问题描述】:

我是 angular 新手,我有一个 textarea,在该 textarea 中键入的任何 HTML 都将在 div 中预览,并且该 div 是可编辑的。因此,如果我修改 div 中的任何内容,应该在 HTML 中反映相同的内容文本区域。假设textarea中有一个<h1> hello world </h1>,它将在div中预览为hello world,我删除了world,然后textarea中的HTML应该变成<h1>hello</h1>。我尝试了this solution 并尝试将 ngModel 添加到 div 中,但两者都不起作用。 this the stackblitz link。谢谢。

export class AppComponent  {
  content = 
`<h2>Hello</h2>
<p>This is a great example...</p>
`;
}
<textarea 
  [(ngModel)]="content"
  cols="50" 
  rows="10">
  </textarea>

<br><br><br>

<div [innerHtml]="content" contenteditable="true">
</div>

【问题讨论】:

  • 好像有错字。看起来您正在尝试使用 contentNew 而不是 content 所以这应该可以解决您当前的绑定问题。 (input)="content=$event.target.textContent"

标签: angular


【解决方案1】:

这样试试

component.html

<textarea 
  [(ngModel)]="content"
  cols="50" 
  rows="10"></textarea>

<br><br><br>

<div [innerHtml]="content" contenteditable="true" (input)="updateModel($event)" #model>
</div> 

component.ts

content = `<h2>Hello</h2>
             <p>This is a great example...</p>
            `;
  updateModel(event) {
     console.log(event.target.innerHTML)
     setTimeout(()=> {
     this.content = event.target.innerHTML;
     }, 1000)
   }

【讨论】:

猜你喜欢
  • 2019-10-12
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 2020-01-02
  • 2017-03-11
  • 1970-01-01
相关资源
最近更新 更多