首页 > 解决方案 > 添加 HTML 代码而不使用 innerHTML 或 insertAdjacentHTML

问题描述

如何在没有 innerHTML 帮助的情况下使用 ts 文件显示数据

const object = {
  piece: 11,
  amount: 2200,
  quantity: 33,
};

this.summaryResult =  `<a class= "nav-Invoice">
  <div>
     <span class="fl" >` + object.piece + `</span>
     <span class="fr" >` + object.quantity + `</span>
     <div class="clearfix"></div>
  </div>
  <span class="divblock">
      <b>$ ` + object.amount + `</b>
  </span>
</a>`

HTML 文件:-

{{summaryResult}}

结果:-

       11                     33
                2200

标签: javascriptangulartypescriptinnerhtml

解决方案


你真的应该用一些 Angular 模板来做到这一点,而不是考虑使用 innerHTML 对象。

摘要.component.ts:

@Component({
  selector: 'app-summary',
  templateUrl: './summary.component.html'
})
export class SummaryComponent {
  public object = {
    piece: 11,
    amount: 2200,
    quantity: 33, 
  };

  constructor() {}

  /* Your object logic here */
}

摘要.component.html:

<a *ngIf="object" class="nav-Invoice">
  <div>
     <span class="fl">{{ object.piece }}</span>
     <span class="fr">{{ object.quantity }}</span>
     <div class="clearfix"></div>
  </div>
  <span class="divblock">
      <b>$ {{ object.amount }}</b>
  </span>
</a>

这两个文件必须在同一个文件夹中,并且组件必须在 Angular 模块中声明。


推荐阅读