【问题标题】:angular: how can we access the class name in the app-root from local component?角度:我们如何从本地组件访问 app-root 中的类名?
【发布时间】:2018-09-10 08:08:15
【问题描述】:

我有三个主要页面和多个子页面,每个页面都从父 css 继承其样式。

country.routes.ts

 ...
 path: '',
 children: [
    { 
      path: '/country', 
      component: CountryComponent, 
      data: {
        cssClass: 'country',
      },
    },
    { 
      path: ':countryId/city', 
      component: CityComponent ,
      data: {
        cssClass: 'country-city',
      },
    },
    {
      path: ':countryId/fact', 
      component: FactComponent,
      data: {
        cssClass: 'country-fact',
      },
    },
...

CSS 类像这样插入到 app-root 正下方的 div 中

index.html(只是粗略的 html 表示)

<app-root>
 <div clas="country/country-fact/country-city">
  <header></header>
  <div>
   <route-outlet>
    <main>
     <!-- content -->
    </main>
   </route-outlet>
  </div>
  <footer></footer>
 </div>
</app-root>

在 main.scss(全局样式)中

country {
  background-color:red;
}
country-city {
  background-color:blue;
}
.country-fact {
  background-color: purple;
}

因为这是有角度的,所以我想利用视图封装并在组件声明器中声明样式

country.component.ts

@组件({

 ...
 styles: ['
  :host-context(.country) main{
    background-color:red;
 ','
   :host-context(.country) header{
     display:none;
    }
 '],

country-city.component.ts

@组件({

 ...
 styles: ['
  :host-context(.country-city) main{
    background-color:blue;
 '],

country-fact.component.ts

@组件({

 ...
 styles: ['
  :host-context(.country) main{
    background-color:purple;
 '],

来自阅读和教程:

我读到了tutorial,所以我在正文或应用程序根级别。

我尝试嵌套:host 或`:host{ :host-context()},都失败了。

https://blog.angular-university.io/angular-host-context/ 中,它说可以使用 puseudo 类在正文级别进行选择,但它不起作用。我读了一些我找不到链接的其他文章,它说:host-context 类似于带有选择器的:host,然后我只能选择我父母的班级而不是正文级别。

【问题讨论】:

  • 您的组件在层次结构中的位置?在&lt;main&gt;??你能在 stackblitz.com 上创建一个小例子吗?
  • 组件在
    下定义
  • 您在下面看到我的答案吗?

标签: html css angular typescript


【解决方案1】:

问题在于main 元素不是您应用样式的组件的一部分

通过阅读host-contexthttps://angular.io/guide/component-styles#host-context)的官方文档,您只能根据组件外部的一些条件将CSS样式应用于组件内部的元素

以下示例将背景色样式应用于组件内部的所有元素,前提是某些祖先元素具有 CSS 类主题光。

:host-context(.theme-light) h2 {
  background-color: #eef;
}

因此,要实现您想要做的事情,您需要在具有main 标签的组件内设置这些样式,或者在您的国家组件内包含main 标签,或者更改规则以定位元素在国家组件内(不是main 标签)

【讨论】:

  • 谢谢,我现在看到 host-context 在父组件的类中选择了一个主题类,而不是 dom 上的任何类。我有时间限制,不确定我是否可以改变,但我会记住下次我做这个的时候。
  • 不,它可以选择 dom 树上的任何类。但您指定的规则仅适用于设置这些规则的组件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多