3

My Requirement is to bind data to dynamically added HTML content. for i.e,

app.component.html

<div>
    <p> {{data.name}} </p>
    <div class="contact" [innerHTML]="htmlContent | safe: 'html'"></div>
<div>

I have created a safe pipe to bind html content.

app.component.ts

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})

export class AppComponet {
    data = {
        name: 'sample',
        mobile: '9999988888',
        email: '[email protected]'
    };
    htmlContent = '';

    constructor() {}

    ngOnInit() {
        this.getDynamicContent();
    }

    // api call to get dynamic content 
    getDynamicContent() {
        this.htmlContent = `<p class="email">Email: {{data.email}}</p>
            <br><p class="mobile">Mobile: {{data.mobile}}</p>`;
    }
}

this is just simple example of my requirements the actual thing is little bit complex. attaching the stackblitz URL for example.

2
  • What is the problem you see? What do you see in your console? Where did you get the safe pipe from? Angular has none pre-defined - for good reasons.
    – christoph
    Commented Feb 8, 2022 at 20:12
  • I have created the custom pipe. check the stackblitz demo. Commented Feb 9, 2022 at 2:04

1 Answer 1

1

Assuming: You will add html content after data is loaded.

Then just replace this:

this.htmlContent = `<p class="email">Email: {{data.email}}</p>
            <br><p class="mobile">Mobile: {{data.mobile}}</p>`;

with:

this.htmlContent = `<p class="email">Email: ${this.data.email}</p>
        <br><p class="mobile">Mobile: ${this.data.mobile}</p>`;

If you are adding content using this.htmlContent then you don't need to use data-binding because you can use the feature of javascript template literals.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.