我真正想做的是将来自后端的文本呈现为具有插值和指令(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/