Angular 5 - 将组件选择器与 InnerHtml 绑定

5 html data-binding innerhtml angular

我有一个名为“app-component1”的 component1 选择器。

@Component({
   selector: 'app-component1',
   templateUrl: './test-widget.component.html',
   styleUrls: ['./test-widget.component.scss'] })
Run Code Online (Sandbox Code Playgroud)

所以调用这个组件的html我通常使用:

<app-component1></app-component1>
Run Code Online (Sandbox Code Playgroud)

它工作得很好。

现在,从另一个 component2 我有以下变量:

variableToBind = "<app-component1></app-component1>";
Run Code Online (Sandbox Code Playgroud)

在组件 2 的 html 中我使用了以下内容:

<div [innerHtml]="varibableToBind"></div>
Run Code Online (Sandbox Code Playgroud)

html 代码绑定不起作用。是否可以帮助我理解原因并也许帮助我找到另一种选择?

小智 5

谢谢大家的建议,我实际上只是找到了答案:

这是行不通的,因为innerHtml是在Angular编译模板之后渲染的。这意味着它目前无法理解您的选择器。

如果你们想动态加载组件(或任何内容),您应该使用 *ngIf。它对我来说效果很好。