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 ''
Updated answer (2017-10-09):
Now I have ng-contenteditable module. Its compatibility with Angular forms.
Old answer (2017-05-11): In my case, I can simple to do:
Where
post
- it's object with propertypostTitle
.First time, after
ngOnInit()
and getpost
from backend, I setthis.postTitle = post.postTitle
in my component.Here's another version, based on @tobek's answer, which also supports html and pasting:
NgModel
expects the bound element to have avalue
property, whichdiv
s don't have. That's why you get theNo value accessor
error.You can set up your own equivalent property and event databinding using the
textContent
property (instead ofvalue
) and theinput
event:Plunker
I don't know if the
input
event is supported on all browsers forcontenteditable
. You could always bind to some keyboard event instead.Working Plunkr here http://plnkr.co/edit/j9fDFc, but relevant code below.
Binding to and manually updating
textContent
wasn't working for me, it doesn't handle line breaks (in Chrome, typing after a line break jumps cursor back to the beginning) but I was able to get it work using a contenteditable model directive from https://www.namekdev.net/2016/01/two-way-binding-to-contenteditable-element-in-angular-2/.I tweaked it to handle multi-line plain text (with
\n
s, not<br>
s) by usingwhite-space: pre-wrap
, and updated it to usekeyup
instead ofblur
. Note that some solutions to this problem use theinput
event which isn't supported on IE or Edge oncontenteditable
elements yet.Here's the code:
Directive:
Usage:
Only tested in Chrome and FF on Linux so far.
I've fiddled around with this solutions and will use the following solution in my project now:
I prefer using the template reference variable to the "$event" stuff.
Related link: https://angular.io/guide/user-input#get-user-input-from-a-template-reference-variable
Here is a simple solution if what you are binding to is a string, no events necessary. Just put a text box input inside the table cell and bind to that. Then format your text box to transparent
HTML: