Home > Net >  Display other content along with innerHTML
Display other content along with innerHTML

Time:01-26

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"  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.

CodePudding user response:

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

CodePudding user response:

Try passing the icon wrapped in a span tag to _getString() method. configure your method such that it returns the icon and the text

E.g getString(icon){ return <span> ${icon} </span> your string here }

in this case every time you call _getString pass the desired icon

  • Related