Search code examples
javascriptangularcontenteditableangular-reactive-forms

How to wrap text within contenteditable with <em> tag when exceeding the character limit


Trying to handle the content of a reactive form control driven by contenteditable and the help of github.com/KostyaTretyak/ng-contenteditable directive.

Please see the StackBlitz where I'm at currently.

<div class="textarea"
    formControlName="description"
    contenteditable="true">
</div>

The contenteditable div is working great as a form control and I have its content as I type with:

this.form.controls['description'].valueChanges.subscribe(
    data => {
        console.log(data)
    })
  • How can I wrap the typed content that is over the character limit with <em> exactly as Twitter's tweet-box version?

twitter's tweet-box with over-limit characters

UPDATE:

Here's some sudo logic I would be applying to the contenteditable content as the user types

characters = 'Lorem ipsum dolor... ' (about 200 characters for testing)

inLimit = characters.substring(0, 140);
outLimit = characters.substring(141);
tagged = '<em>' + outLimit + '</em>';
final = inLimit + tagged;
console.log(final); // over the limit characters wrapped in <em> tag

Solution

  • That was quite fun :) See result https://stackblitz.com/edit/angular-b4mzej . It still have some weird bug with jumping cursor after first application and characters count once you added value then cleared it and try adding again starting from the point when 0 characters left, but when I debugged it I realized that stackblitz itself changing code slightly, so I believe it should work fine under normal conditions.

    Main trick was to use proper propValueAccessor, see https://github.com/KostyaTretyak/ng-contenteditable#options