Search code examples
htmlangulartypescriptangular-directive

Interpolate html strings in Angular


I have html that looks like this:

<div *ngFor="let s of project.sections">
    <div class="project-desc-section">
         <h2>{{s.heading}}</h2>
         <div *ngFor="let w of s.work">
             {{w}}
         </div>
    </div>
</div>

My Project objects look like this

{ 
                name: "Project Name",
                id:"bbs",
                isClicked:false,
                description:`Sick app description`,
                sections:[
                            {
                                heading: "Mr header",
                                work:[
                                    '<p>Some cool stuff to talk about</p>',
                                    '<img src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif">'
                                    
                                ] 
                            }
                    
                ]
            },

And these are the actual classes if anyone is curious:

export class Project{

    name:string;
    id:string;
    description:string;
    isClicked:boolean;
    sections:Section[];
    
   
    constructor(id:string,name:string,description:string,isClicked:boolean,sections:Section[]) {
        this.id=id;
        this.name = name;
        this.description = description;
        this.isClicked = isClicked;
        this.sections = sections;
    }
}

export class Section{

    heading:string;
    work:HTMLElement[];
    
    
    constructor(heading:string,work:HTMLElement[]) {
        this.heading = heading;
        this.work = work;
    }
}

To nobodies surprise, angular doesn't compile the HTML, it just interpolates them as strings: HTML result

So is there any way I can force angular to compile the HTML? I know this isn't the "Angular Way", but this is my personal website so I'm taking full liberties here. I also agree if you think the way I structured this was a poor design choice, but I'm already too far down this rabbit hole!


Solution

  • You can use for this innerHTML property.

    Example:

    <div [innerHTML]="yourVariable"></div>