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?

TheDude
  • 3,045
  • 4
  • 46
  • 95
  • 1
    How about using `ng-content`? https://scotch.io/tutorials/angular-2-transclusion-using-ng-content – Harry Ninh Jun 22 '17 at 03: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? – dee zg Jun 22 '17 at 03:38
  • @HarryNinh: Thanks, I'm going to look at it, I'll be back shortly – TheDude Jun 22 '17 at 03: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 – TheDude Jun 22 '17 at 03:41
  • 1
    @TheDude 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) – LLai Jun 22 '17 at 03:45
  • @LLai: Brilliant! If you post your comment as an answer, I'll accept it! – TheDude Jun 22 '17 at 03:49

1 Answers1

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>
LLai
  • 13,128
  • 3
  • 41
  • 45
  • An issue with using [innerHTML] is that it will only work with browsers and not other rendering engines. – Sean12 Oct 16 '17 at 15:01
  • @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 – LLai Oct 16 '17 at 15:09