在Angular中插值html字符串

问题描述

我有这样的html:

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

我的Project对象看起来像这样

{ 
                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">'
                                    
                                ] 
                            }
                    
                ]
            },

如果有人好奇,这些是实际的课程:

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;
    }
}

令人惊讶的是,angular不会编译HTML,它只是将它们作为字符串插入:

HTML result

那么我有什么方法可以强制angular来编译HTML?我知道这不是“ Angular Way”,但这是我的个人网站,因此我在这里享有全部自由。我也同意,如果您认为我的结构方式不是一个好的设计选择,但是我已经远远超出了这个难题!

解决方法

您可以使用此innerHTML属性。

示例:

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