1
votes

I would like to wrap the selected text in div paragram which with a custom component.

I know we can wrap text in <span>, <b>, etc. tag using :

let selection = window.getSelection();
let range = selection?.getRangeAt(0);
let selectedText = selection?.toString();
range.insertNode(document.createTextNode(`<span>${selectedText}</span>`));

But how to wrap in a custom component of angular? Let's say we have a component SpecialComponent with the selector as <app-special>

So DOM should be something like :

Lorem Ipsum has been the <app-special>industry's standard dummy text ever since</app-special>the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

1
Maybe <div [innerHTML]="someControllerStringWithHtmlTags"></div> ?Deunz
@Brandon Content-projection will me pass the text content inside the component, but how will I inject the custom component in DOM in place of selected text?Chinmay Padole
@Deunz That won't help me inject the component over selected text.Chinmay Padole
I'm not understanding what you're needing to accomplish. Content projection will allow you to wrap whatever content you want, e.g.: <app-comp1>some <app-comp2>more</app-comp2> text</app-comp1>. Is that what you're looking for?Brandon

1 Answers

0
votes

Let's say your custom component SpecialComponent has an input that takes a string parameter customSentence, then passing a string sentence into the component is done as follows:

Lorem Ipsum has been the 
<app-special [customSentence]="'industry's standard dummy text ever since'">
</app-special>
the 1500s, when an unknown printer took a galley of type and scrambled it to 
make a type specimen book.

Within your custom component, create an input decorator to receive the sentence and a getter as follows:

private _customSentence: string = '';

...

@Input() 
set customSentence(value: string)
{
  this._customSentence = value;
}
get customSentence()
{
  return this._customSentence;
}

Your custom component HTML template will be:

<span>{{customSentence}}</span>

This will be sufficient to render your custom component within another component.