Home  >  Q&A  >  body text

Display other content and innerHTML simultaneously

I have a component that renders labels based on passed data like this:

<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 next to each text when needed.

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

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

Is there any way to render the icon (using ng-content or something similar, since I don't want to write the icon html in every element) and the innerHTML data?

I'm new to the Angular world, so I'm trying to learn. Any help would be greatly appreciated.

Thanks.

P粉727531237P粉727531237210 days ago335

reply all(1)I'll reply

  • P粉731977554

    P粉7319775542024-03-23 09:55:28

    It seems that your problem is not specific to Angular, but JavaScript behavior.

    innerHTML Gets or sets the HTML or XML tag contained in the element. So that means it replaces whatever was there in the first place. (https://developer.mozilla.org/en-US /docs/Web/API/Element/innerHTML)

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

    reply
    0
  • Cancelreply