Wrap certain words with a component in a contenteditable div in angular

Viewed 393

I'm trying to replace a dynamic text that comes from a contenteditable div, sort words via regex and wrap them with an angular component.

So far I've found a way to replace that text with the component tag, but I can't seem to make the component work. Instead, it just shows the component as blank.

How can I manually bootstrap/fire-up these dynamically added components?

app.component.html:

<div #from_field (keyup)="textarea_keyup_event(from_field)" contenteditable="true">
  This text can be edited by the user.
  If the user writes the 'moo' word, it should be wrapped with "replacer" component.
</div>

app.component.ts:

function getFormattedText(text) {
    var parts = text.split(/(\bmoo+\b)/gi);
    for (var i = 1; i < parts.length; i += 2) {
      parts[i] = '<app-replacer key="'+ i + '">' + parts[i] + '</app-replacer>';
    }
    return parts.join('');
}
textarea_keyup_event(element) {
  const preFormattedText = element.textContent;
  element.innerHTML = getFormattedText(preFormattedText);
}

// if you write:
// "I am a cow; cows say moo. MOOOOO."
// it replaces the DOM with this:
// "I am a cow; cows say <app-replacer key="1">moo</app-replacer>. <app-replacer key="3">MOOOOO</app-replacer>."
// but the app-replacer tag doesn't fire up the component.
1 Answers

I would do it with the help of a web component.

Angular has a @angular/elements library that allows us to create a web component from Angular component.

app.module.ts

import { createCustomElement } from '@angular/elements';

@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: [
    AppComponent,
    ReplacerComponent
  ],
  entryComponents: [ReplacerComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(private injector: Injector) {
    if (!customElements.get('app-replacer')) {
      const btnComp = createCustomElement(ReplacerComponent, {
        injector: this.injector
      });
      customElements.define('app-replacer', btnComp);
    }
  }
}

Once you defined ReplacerComponent as a web component all app-replacer tags in your contenteditable div will be automatically rendered as a components.

Ng-run Example

Related