0

So I want to display a html string in my template. To do this I use this in my html file:

<div [innerHTML]="myObject.string | safeHtml"></div>

Where safeHtml is a pipe to mark the html string as trusted, like explained here for example. This is my component.ts:

import { Component } from '@angular/core';

@Component({
    templateUrl: "my html file"
})
export class MyComponent {
    myObject;
    variable;

    constructor() {
        this.variable = "hello";
        this.myObject = {string: "text text <b [innerHTML]='variable | safeHtml'></b> text text" };
    }
}

Right now this is displayed in the <div>: text text text text. When I inspect this in my browser, there is an <b> tag also where it should be, but it's empty, like: <b [innerHTML]="variable | safeHtml"></b>.

I don't want to do something like this where myObject.string is:

"text text <b>" + this.variable + "</b>text text"

That's because myObject actually is in another component and it doesn't has a link to this.variable (I don't know if that's good practise).


Can anyone help me with this to display the variable within a html string? I hope I explained it good enough. Thanks!

Community
  • 1
  • 1
user3050534
  • 227
  • 4
  • 17
  • Can you show the `myString` ? – Sampath Apr 13 '17 at 10:51
  • I'm not sure what you mean @Sampath, the content of `myString` is in my question, currently it's: `"text text text text"` – user3050534 Apr 13 '17 at 10:57
  • Can you show your `JSON object`? – Sampath Apr 13 '17 at 11:00
  • sorry for off topic, but may i know what is `safeHtml` here ? – Pardeep Jain Apr 13 '17 at 11:02
  • 1
    @Sampath, it's like: `this.object = { string: "text text .. " }`, it really is nothing special. And everything is working fine, except for the `variable`, which is empty. @PardeepJain, in my question I linked to a post where it's explained: [here] (http://stackoverflow.com/questions/31548311/angular-2-html-binding/41089093#41089093) – user3050534 Apr 13 '17 at 11:05
  • What is `variable` then? – Sampath Apr 13 '17 at 11:09
  • @Sampath, currently nothing more than `this.variable = "hello"`. I'm sorry if I'm not explaining well. – user3050534 Apr 13 '17 at 11:14
  • 1
    I think you'll need to show the component code fully so we can see how you've set up the template code and the properties of the component.ts – aaron-bond Apr 13 '17 at 11:17
  • Why are you changing the innerHtml of the `` tag? You're outputting the HTML from code, so why not just interpolate the string you want inside the `SomeStringHere` tags? – aaron-bond Apr 13 '17 at 14:51

0 Answers0