menu

Questions & Answers

Display other content along with innerHTML

I have a component where it renders the tags depends on the data passed as shown below:

<ng-container>
<ng-container [ngSwitch]="tag">
    <p    *ngSwitchCase="'p'"  [innerHTML]="_getString()"></p>
    <h1   *ngSwitchCase="'h1'" [innerHTML]="_getString()"></h1>
    <h2   *ngSwitchCase="'h2'" [innerHTML]="_getString()"></h2>
    <h3   *ngSwitchCase="'h3'" [innerHTML]="_getString()"></h3>
    <h4   *ngSwitchCase="'h4'" [innerHTML]="_getString()"></h4>
    <span *ngSwitchCase="'span'" [innerHTML]="_getString()"></span>
    <code *ngSwitchCase="'code'" [innerHTML]="_getString()"></code>
    <time *ngSwitchCase="'time'" [innerHTML]="_getString()"></time>
</ng-container>

I want to render an icon beside each text whenever required.

<span *ngIf="icon" class="css-{{icon}}" role="presentation"></span>

If I put the icon tag in between each tag, it gets replaced by the innerHTML data.

Is there any way I can render both the icon(using ng-content or something like that because I dont want to write the icon html inside every element) and innerHTML data?

I am new to Angular world so trying to learn. Any help would be appreciated.

Thank you.

Answers(1) :

It seems that your question is not specific for Angular, but a JavaScript behavior.

innerHTML gets or sets the HTML or XML markup contained within the element. So it means that it replaces whatever content was there to start with. (https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML)

I think you can try using insertAdjacentHTML() instead - this should add HTML to the element that's already present there in the DOM. Check the syntax and examples here: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

Comments:
2023-01-25 14:42:03
Thanks for the reply but I am looking for a solution in the Angular world and dont want to write a javascript code to append an element.