【问题标题】:Styling not applying to child component样式不适用于子组件
【发布时间】:2016-12-12 09:16:58
【问题描述】:

我正在尝试将样式应用于子组件标签,但我不能这样做。

我有带有锚标记的子组件。

尽管我在父组件中有锚标记的样式,但它不适用。有什么解决办法?

工作代码:http://plnkr.co/edit/CJCpV4ZbG7hdxT2AeSmt?p=preview

 <a href="https://www.google.com">Google</a>

在父组件中,我使用子组件并为此子组件应用样式。

HTML代码:

<div class="container">
  <div class="test">
    <testapp></testapp>
  </div>
</div>

CSS代码:

.container{
  font-family:sans-serif;
  font-size:18px;
  border: 1px solid black;
}
.test{
  width:50%;
  background-color:#f0f5f5;
}

.container:hover .test{
  background-color:#e6ffe6;
}
.container:hover .test:hover{
  background-color:#ffffe6;
}
.container .test a {
    color:   red ;
}
.container .test a:hover {
    color:green;
}

【问题讨论】:

    标签: css angular


    【解决方案1】:

    这是因为默认组件有视图封装(shadow dom)。要禁用此行为,您可以利用encapsulation 属性,如下所述:

    import {Component, ViewEncapsulation} from '@angular/core';
    import {TestApp} from 'testapp.component.ts';
    @Component({
      selector:'test-component',
      styleUrls: ['test.component.css'],
      templateUrl: './test.component.html',
      directives:[TestApp],
      encapsulation: ViewEncapsulation.None // <------
    })
    export class TestComponent{
    
    }
    

    看到这个 plunkr:http://plnkr.co/edit/qkhkfxPjgKus4WM9j9qg?p=preview

    【讨论】:

    • 如果您不介意,能否请您解释一下您的解决方案 虽然它可以工作,但我不知道为什么它以前不起作用。
    • 样式直接应用于组件只适用于该组件,它不适用于其他组件,因为“视图封装”,即视图被封装到组件。这个答案解决了问题,但它有效地使其样式全球化,并可能导致 SPA 设计出现问题,因为它在功能上编写了标准期望的异常。
    【解决方案2】:

    当使用 styleUrls 属性时,样式对于一个组件是本地的,而不是它的子组件。所以我做了两个改变: 1) 将 styleUrls 移至 testapp 组件。 2) 将 div 移至 testapp 组件。

    import {Component} from '@angular/core';
    @Component({
     selector:'testapp',
     styleUrls: ['./test.component.css'],
     template: `
     <div class="test">
      <a href="https://www.google.com">Google</a>
     </div>
    
     `
    
    })
    export class TestApp{
    
    }
    

    【讨论】:

      【解决方案3】:

      已编辑:这应该可以解决:

      在子类的css中写下代码

      :host.parentclass childclass{
      
      }
      

      父类是子类的直接父类。 childclass 是应用于子组件的类。

      【讨论】: