'Angular 13: Dynamic Html with data binding

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source