角度指令和插值不适用于动态html代码

时间:2018-07-30 13:31:57

标签: angular interpolation dynamic-data

我想做的就是将来自后端的文本作为角度模板的一部分进行渲染,并具有内插和指令(ngfor,if,switch)等完整功能。

这是一个简短的示例

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

3 个答案:

答案 0 :(得分:1)

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

说在服务器响应(以http为例)出现后,您调用 handleResponse()函数。

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

您的 HTML 文件将保持不变

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

通过这种方式,您可以构造应显示的html。

答案 1 :(得分:0)

应该是这样的:

name = `world!`;
sample = '<span>hello '+this.name+'</span>';

和html中的

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

答案 2 :(得分:0)

说在服务器响应(以http为例)出现后,您调用 handleResponse()函数。

handleResponse(response) {
    this.name = response.name
    // ...
}

然后在您的 HTML文件

<span>hello <span>{{name}}</span></span>

这是正常的角度练习。此外,它也很容易实现。