4

How can I add a html element dynamically using string interpolation without add any html tag? Exp:

This is my obj in my component

myObj = {
    title: 'Header Title',
    icon: '<i class="fa fa-user">'
}

I want to add this like;

<header>
    {{myObj.title}} - {{myObj.icon}}
</header>

{{myObj.icon}} rendered as text, but I want render as html. How can?

I want the result to be as follows

<header>
    Header Title <i class ="fa fa-user"></i>
</header>

and if I change my obj like this;

myObj = {
    title: 'Header Title',
    icon: '<mat-icon>search</mat-icon>'
}

render as

<header>
    Header Title <mat-icon>search</mat-icon>
</header>
2
  • 1
    Possible duplicate of Angular HTML binding Commented Oct 19, 2018 at 13:29
  • 1
    Try: <header [innerHTML]="myObj.title + ' - ' + myObj.icon">. I don't know if it works for the i tag however. Commented Oct 19, 2018 at 13:31

1 Answer 1

7

You can leverage innerHTML

<header>
    <span>{{myObj.title}}</span> - <span [innerHTML]="myObj.icon"></span>
</header>

Note : I have used to segregated the elements however you can pick any element as per your design.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks but i want to make it without adding any html tag as span
Use DomSanitizer or DomSanitizationService
@SunilSingh could you give us an example usage of DomSanitizer in this context?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.