如何在angular中动态添加class 4

How to add class dynamically in angular 4

我正在做一个使用angular 的项目 4,我如何将class 添加到index.html 的正文中。例如

   <body class="home">
      <app-root></app-root>

   </body>

我希望仅在我的 HomeComponent 为任何其他 pages/component

加载和移除时才添加此 class

大家干杯。

您不能真正使用 index.html 中的 Angular 功能。我建议对您的应用程序结构采用不同的方法。

将您的 app-root 组件定义为仅 router-outlet。然后用你的菜单构建一个 shell 组件,header,以及你想要的 "home".

的任何其他样式

然后,您可以将任何不带样式的页面直接路由到 app-root 的 router-outlet,并将任何带样式的页面路由到 shell 组件。

我这里有一个这样设置的例子:https://github.com/DeborahK/MovieHunter-routing

app.component.html

<router-outlet></router-outlet>

shell.component.html

<mh-menu></mh-menu>

<div class='container'>
    <router-outlet></router-outlet>
</div>