How to use [(ngModel)] on div's contenteditable in angular2?
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 ''
Solution 1:
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.
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(); }
}
Plunker
I don't know if the input
event is supported on all browsers for contenteditable
. You could always bind to some keyboard event instead.
Solution 2:
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:
<div
contenteditable="true"
(input)="post.postTitle = $event.target.innerText"
>{{ postTitle }}</div>
Where post
- it's object with property postTitle
.
First time, after ngOnInit()
and get post
from backend, I set this.postTitle = post.postTitle
in my component.