ngModel不使用contenteditable处理<div>标记并将html作为输入

时间:2017-11-03 10:20:49

标签: angular

我正在尝试绑定我的输入,即包含html内容的字符串。 app.component.ts有&#39;内容&#39;变量

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上应用2路绑定与contenteditable = true。

3 个答案:

答案 0 :(得分:0)

要使用值绑定,请执行此操作

<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);
   }
}

答案 1 :(得分:0)

试试这样:

<强>模板

<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

答案 2 :(得分:0)

我尝试了以下方式,并且工作正常。 尝试一下

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