首页 > 解决方案 > 将 Html 与 Angular 中的变量绑定

问题描述

我需要从后面渲染一些 HTML。像这样的东西:

<strong> Item label: {{item.label}}</strong>

我尝试这样做:

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

但它的渲染:

Item label: {{item.label}}

但我有项目对象

  item = {
    label : 'Label from item'   }

我需要渲染

Item label: Label from item

我创建一个例子:

https://stackblitz.com/edit/angular-htmlwithvariables

标签: htmlangulartypescript

解决方案


使用 ES6 字符串插值


    @Component({
      selector: 'app-component',
      template: '<div [innerHtml]="html" ></div>',
      styleUrls: [ './app.component.scss' ]
    })
    export class AppComponent {
    
      item = {
        label: 'Label from item'
      };
      html: any = `<strong> Item label: ${this.item.label}</strong>`;
      
      constructor() { }
    
    }

模板字符串使用反引号 (``) 而不是单引号或双引号。

模板字符串可以使用占位符使用 ${ } 语法进行字符串替换。


推荐阅读