11

I've searched the web but can't find a way to work with contenteditable events on Angular 6/7. Angular seems to have a messy solution with it but said feature doesn't seem to be carried over to recent versions.

A use case would be is on a content editable onChange event, call a function:

<div contententeditable="true" [change]="onNameChange(if.there.is.such.a.thing)">Type your name</div>

...

private name: string;

onNameChange(name) {
   this.name = name;
}

Any ideas on this? Thanks.

Jhourlad Estrella
  • 3,545
  • 4
  • 37
  • 66

2 Answers2

31

You can use the input event, like so:

<div contenteditable (input)="onNameChange($event.target.innerHTML)">
   Type your name
</div>

Here is a Stackblitz demo

user184994
  • 17,791
  • 1
  • 46
  • 52
  • Thank you for your answer. Would it be possible to include in your answer how the innerHtml is passed to the callback function? – Jhourlad Estrella Nov 03 '18 at 10:59
  • @JhourladEstrella Sure, I've updated the answer and the example – user184994 Nov 03 '18 at 11:03
  • How would you set an initial value (i.e. a previously saved value)? Also if the text has line breaks or tabs or whatnot you'd have to manually convert them to/from html tags. This really doesn't seem like a viable option for the most common use case of an expanding input, which is long runs of text. – Emperor Eto Mar 03 '21 at 14:14
0

Just set a variable on element and on event input, get value from innerText

<h2 contenteditable="true" #x (input)="item.title = x.innerText">{{item.title}}</h2>

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 18 '22 at 20:59