0

我想将来自 API 的传入文本呈现为后续的 HTML 和组件模板。我在这里找到的大多数解决方案都使用 @ViewChild 来注入组件,但这对我不起作用,因为我需要为 *ngFor 循环中的所有项目迭代相同的行为。

这就是代码的样子:

渲染传入消息的组件模板:

      <div *ngFor="let item of messages">
            <compile-component [template]="item.html"></compile-component>
      </div>

传入消息结构(item.html):

<my-component></my-component><div>Some html</div>

要编译的组件:

@Component({
  selector: 'my-component',
  template: '<div>It works</div>',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent{ }

输出如下所示:

<div>It works</div><div>Some html</div>

我在这里寻找编译组件的解决方案。任何帮助深表感谢。提前致谢。

4

1 回答 1

0

您应该可以通过ComponentFactoryResolver. 在此处查看有关此的角度文档:

https://angular.io/guide/dynamic-component-loader

于 2017-10-24T15:08:48.630 回答