如何在 angular2 中对 div 的 contenteditable 使用 [(ngModel)]? [英] How to use [(ngModel)] on div's contenteditable in angular2?
问题描述
我正在尝试使用 ngModel 以两种方式绑定 div 的 contenteditable 输入内容,如下所示:
I am trying to use ngModel to two way bind div's contenteditable input content as follows:
<div id="replyiput" class="btn-input" [(ngModel)]="replyContent" contenteditable="true" data-text="type..." style="outline: none;" ></div>
但它不起作用并发生错误:
but it is not working and an error occurs:
EXCEPTION: No value accessor for '' in [ddd in PostContent@64:141]
app.bundle.js:33898 ORIGINAL EXCEPTION: No value accessor for ''
推荐答案
NgModel
期望绑定的元素有一个 value
属性,div
s 没有.这就是您收到 No value accessor
错误的原因.
NgModel
expects the bound element to have a value
property, which div
s don't have. That's why you get the No value accessor
error.
您可以使用 textContent
属性(而不是 value
)和 input
事件来设置自己的等效属性和事件数据绑定:
You can set up your own equivalent property and event databinding using the textContent
property (instead of value
) and the input
event:
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `{{title}}
<div contenteditable="true"
[textContent]="model" (input)="model=$event.target.textContent"></div>
<p>{{model}}`
})
export class AppComponent {
title = 'Angular 2 RC.4';
model = 'some text';
constructor() { console.clear(); }
}
我不知道是否所有浏览器都支持 contenteditable
的 input
事件.你总是可以绑定到一些键盘事件.
I don't know if the input
event is supported on all browsers for contenteditable
. You could always bind to some keyboard event instead.
这篇关于如何在 angular2 中对 div 的 contenteditable 使用 [(ngModel)]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!