如何使用Angular 6中的模拟封装更改子组件样式?

时间:2018-12-12 20:24:34

标签: angular css3 angular6

如何在不更改封装视图的情况下从父级更新某些子组件css?

以下是示例demo

app.component.ts

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

hello.component.ts

import { Component, Input } from '@angular/core';

@Component({
 selector: 'hello',
  template: `<h1 class='test'>Hello {{name}}!</h1>`,
  styles: [`.test { font-family: Lato;color:red; }`]
})
export class HelloComponent  {
  @Input() name: string;
}

app.component.css

:host ::ng-deep .test{
  color:green;
}

p {
  font-family: Lato;
}

我在chrome工具栏中可以看到它试图覆盖样式,但是子组件仍然显示color:red。

enter image description here

2 个答案:

答案 0 :(得分:2)

在CSS上几乎缺少一件事。

:host ::ng-deep hello .test{
  color:green;
}

其中hello是组件选择器。

https://stackblitz.com/edit/angular-74ajje

答案 1 :(得分:1)

:host伪选择器以组件的主机 element 为目标(例如<app-hello>,这是其自身标记中不可用的元素)。听起来很简单。

::ng-deep有所不同。当Angular编译组件样式时,此选择器将导致样式在所有子组件中作为其自身封装的上下文的一部分向下遍历。

您使用:host ::ng-deep .test {所说的是“宿主元素[_nghost-c1]的目标后代以及所有属于class =“ test”宿主元素的子元素。

封装在该组件中的规则.test {说:“使用class =“ test”定位此组件中的每个元素(编译为[_ngcontent-c1])。

由于h1是主机的后代,但是该组件的直接成员,因此后者是一个更特定的规则,并赢得了CSS之战。