Search code examples
angulardata-bindingangular13

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: 'temp@mail.com'
    };
    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.


Solution

  • 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.