4

I need to pass an html string to a component in angular 4, but I can't find a way to mark the passed string as safe.

I'm creating the passed html in parent component, it's not something I get from user or retrieve from server, it's also dynamic (created depending on the situation / alert type)

My code looks like this:

<app-alert
  message = "Please complete your <span class=u>Profile</span>"
  alertType = "alert-info"
  icon = "glyphicon glyphicon-info-sign"
  closeBtn = "true">
</app-alert>

I searched a lot, but I couldn't find something suitable, the closest I could find is this question, but it only deals with "normal" strings, not strings that contains html in it

How can I pass an html string to my child component?

6
  • 1
    How about using ng-content? scotch.io/tutorials/angular-2-transclusion-using-ng-content Commented Jun 22, 2017 at 3:36
  • smells like a bad design. why couldnt you wrap all info you need into object, pass it to component and then have html as part of child component, fill it and show it from child? Commented Jun 22, 2017 at 3:38
  • @HarryNinh: Thanks, I'm going to look at it, I'll be back shortly Commented Jun 22, 2017 at 3:39
  • @deezg You're kind of right, but as I said, the html is dynamic, and...hum...yeah you may be right, an object would probably the right way to do it Commented Jun 22, 2017 at 3:41
  • 1
    @TheDude you could pass the html string as a component input. then within your child component's html use the innerHTML directive (dev6.com/Angular-2-HTML-binding) Commented Jun 22, 2017 at 3:45

1 Answer 1

11

you could pass the html string as a component input. then within your child component's html use the innerHTML directive (https://www.dev6.com/Angular-2-HTML-binding)

<span [innerHTML]="componentInput"></span>
Sign up to request clarification or add additional context in comments.

2 Comments

An issue with using [innerHTML] is that it will only work with browsers and not other rendering engines.
@Sean12 I believe the OP did a similar thing to you, and created the string in his parent, then passed it to a child with the Input directive. What do you mean by the string is not passed in full? The string is passed through the input directive, then is used in the innerHTML directive to insert html + text within the span tags

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.