angular: Angular ngModel can't support div(contentEditable=true)
not work
<div [(ngModel)]="text" contentEditable=true></div>
<div>{{text}}</div>
if change div to textarea,it’s work fine.
<textarea [(ngModel)]="text" contentEditable=true></textarea>
<div>{{text}}</div>
i hope ngModel can support div(contentEditable=true)
About this issue
- Original URL
- State: open
- Created 8 years ago
- Reactions: 14
- Comments: 22 (4 by maintainers)
@zoechi Has a problem in your link that after every input. the cursor’s position will be reset.below is my code:
<div #box contenteditable="true" [innerHtml]="content" (input)="content=$event.srcElement.innerHTML"></div>
so how to bind innerHtml(div) to content(variable) and does not affect user input?@keyiis and @rhyeen, the reason the cursor resets after the input event is because the event is telling Angular to update the model, triggering another change to the innerHTML. To get around this, you can use a temporary “revised” model where the changes get saved.
For example:
<div #box contenteditable="true" (input)="revisedContent=$event.srcElement.innerHTML">{{content}}</div>
If needed, the original model can be updated on the blur event or at a time where it doesn’t matter if it overwrites the innerHTML of the div.
For a workaround see http://stackoverflow.com/questions/35378087/how-to-use-ngmodel-on-divs-contenteditable-in-angular2
@KostyaTretyak awesome work there! I wish Angular and Material2 would support contenteditable much better than it does.
To work properly, it is necessary to implement ControlValueAccessor for the directive
contenteditable
. See my solution: @ng-stack/forms.Second confirmation of @keyiis problem, although I notice it in Chrome as well. If you change the cursor position within the
contenteditable
DOM element, it will reset the cursor to the beginning of the element.I confirm @keyiis words. It’s really a problem. Happens in Firefox, in Chrome it seems to be allright.