【问题标题】:how to make Angular Component appear in HTML template?如何使 Angular 组件出现在 HTML 模板中?
【发布时间】:2019-04-15 00:30:10
【问题描述】:

我正在使用 Angular 6 开发一个网络应用程序。我有一个小问题:在我的一项服务中使用这个简单的代码:

method() {
   document.body.insertAdjacentHTML('beforeend', '<h1>Hello</h1>');
}

我可以在每次运行时动态显示 html 代码。然而,发生这种情况只是因为它是一个原生 HTML 标记。如何使用与 HTML 模板关联的 Angular 组件做同样的事情?比如 ,这样就不行了……

method() {
  document.body.insertAdjacentHTML('beforeend','<myComponent>/myComponent>');
}

您能帮我提供一个使用几行代码的解决方案吗?我必须在服务中使用这种方法。谢谢。

【问题讨论】:

标签: html angular typescript components


【解决方案1】:

您应该将组件放入 DOM 并使用 *ngIf 或其他一些保护来决定何时显示它:

<myComponent *ngIf="showComponent"></myComponent>

变量showComponent 将根据您关于何时显示组件的条件设置为真/假。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2023-03-11
    • 2020-04-19
    相关资源
    最近更新 更多