Angular Directive(指令)和插值不适用于动态 html 代码

标签 angular interpolation dynamic-data

我真正想做的是将来自后端的文本呈现为具有插值和指令(ngfor、if、switch)等完整功能的 Angular 模板的一部分。

这是一个简单的例子

template.component.ts

import { Component, OnInit } from '@angular/core';
import { MyService } from '../my.service';
@Component({
  selector: 'app-template',
  templateUrl: './template.component.html',
  styleUrls: ['./template.component.scss']
})
export class TemplateComponent implements OnInit {
  names: string[];
  template: string;
  constructor(
    private myService: MyService
  ) { }

  ngOnInit() {
      this.myService.getTemplate('page-name').subscribe(data => {
        // say data = <span *ngFor="let name of names">hello {{name}}</span>
        this.template = data;
      });
      this.myService.getNames().subscribe(data => {
        // say data = ['name 1', 'name 2', 'name 3']
        this.names = data;
      });
  }

}

template.component.html

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

当前输出

hello {{name}}

期望的输出

hello name 1
hello name 2
hello name 3

这是我找到的最接近我需要的东西 https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e

最佳答案

你不能像下面那样做吗?当数据更新时,您可以重新生成样本。

假设在您的服务器响应到来后(在您的例子中是 http),您调用了 handleResponse() 函数。

handleResponse(response) {
    this.sample = `<span>hello <span>` + this.name + '</span></span>`;
    // ...
}

您的 HTML 文件将保持不变

以类似的方式,您可以使用 if, else 等而不是 inIf...

这样就可以构造出应该显示的html了。

关于 Angular Directive(指令)和插值不适用于动态 html 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51595152/

相关文章:

angular - 如何创建 Angular 9 项目?

angular - 浏览器中文件下载进度 : Angular 5

angular - 如何使用 Angular CLI 包含自定义样式

Java swt 图像插值

python - 三次样条内存错误

python - 在访问 python 中的对象时返回默认成员

c# - 我可以通过 Linq to Sql 合并字段吗

html - 无法将单选按钮与标签分开

css - 如何在 Angular 组件的样式标签中使用字符串插值?

javascript - 来自数据库的 Django 动态下拉列表