【问题标题】:Dynamic Variable Compilation in Angular 7Angular 7 中的动态变量编译
【发布时间】:2019-12-09 16:56:45
【问题描述】:

我需要使用 Angular 7 在 HTML 模板中实现动态变量编译。

这是我的示例代码:

app.component.ts:

username = 'User Name';
sampleData = "This is my <strong>{{username}}</strong>";

app.component.html:

<div [innerHtml]="sampleData"></div>

但是,输出仍然是

This is my {{username}}.

我的预期输出是,

This is my UserName

使用$compile 可以在Angular 1 中实现相同的功能。请让我知道如何在 Angular 7 中实现这一目标

【问题讨论】:

标签: javascript html css json angular


【解决方案1】:

试试这个:

username = 'User Name';
sampleData = "This is my <strong>" + this.username + "</strong>";

根据您的评论,对于动态 tdata,您可以这样做:

username = 'User Name';
sampleData = "This is my {{username}}";

ngOnInit() {
   this.sampleData = this.sampleData.replace("{{username}}", `<strong> ${this.username} </strong>`)
}

【讨论】:

  • 变量 sampleData 是动态的,将存储在单独的 json 中。因此我需要在 html 中编译它而不是直接数据插值。
  • @GaneshBabu 您可以根据ngOnInit()中的要求编译您的字符串
【解决方案2】:

您可以使用 ng-template 并为其创建本地引用,并将其与 ngTemplateOutlet 一起使用,您可以在其中传入动态内容。

HTML(模板)


<ng-template #temp let-item>
  <div> This is my variable <strong>{{ item }}</strong> which is dynmically parsed. </div>
</ng-template>

<ng-container *ngTemplateOutlet="temp; context: { $implicit: name }"></ng-container>

打字稿

export class AppComponent  {
  name = 'Angular';
}

查看 stackblitz 演示 - https://stackblitz.com/edit/angular-lec12u

【讨论】:

  • 我们需要将“
    这是我的变量 {{ item }} 动态解析。
    ”存储在组件内部的变量中。上述解决方案不适用于这种情况
猜你喜欢
  • 1970-01-01
  • 2020-03-18
  • 2019-08-05
  • 1970-01-01
  • 2015-04-03
  • 2017-05-03
  • 1970-01-01
  • 2020-10-15
  • 2023-04-10
相关资源
最近更新 更多