Search code examples
javascripthtmlangularangularjs-ng-includeangular5

Angular: How to implement ng-include like functionality in Angular 5?


Is there any functionality to render html file dynamically inside a components template based on the path? I have the path to local html file now I need to display the content of it inside a components template. In Anular 1.x we had ng-include, any similar functionality in Angular5?

<div class="row blogdetail-container">
        {{blogSelected.description}} // currently interpolates the path
</div>

variable blogSelected.description contains the path to html file and I want to replace its content here.


Solution

  • Okay so the only reasonably straight-forward way I can think of to do this is to use an http request to get the contents of the html file then use that in the [innerHtml] attribute.

    private dynamicTemplate: any = ""; http.get(blogSelected.description).map((html:any) => this.dynamicTemplate = sanitizer.sanitize(html));

    then use

    <div class="row blogdetail-container" [innerHtml]="dynamicTemplate"></div>
    

    NOTE 1: remember to include http as a dependency for this component.

    NOTE 2: remember to include sanitizer as a dependency for this component

    NOTE 3: remember to validate blogSelected.description before calling the http request to check it's actually a valid URL.