3

如何禁用 ViewEncapsulation.None 的效果?例如,我的一个组件 (firstComponent) 定义了一个带有一些属性的 css 类。有 secondComponent 使用相同的 css 类。我希望我的“secondComponent”对第一个组件样式表定义的属性使用不同的特定值。我怎样才能做到这一点?

注意:我用不同的值在“secondComponent”中重新定义了同一个类,保持 secondComponent 默认的 viewEncapsulation。它对我不起作用。

FirstComponent:
@Component({
    moduleId: module.id,
    selector: "FirstComponent",
    templateUrl: 'FirstComponent.component.html',
    styleUrls: ['FirstComponent.component.css'],
    encapsulation: ViewEncapsulation.None
})
FirstComponent.component.css

.ui-tree .ui-tree-container {
    background-color: #252525;
    color: white;
}

Second Component:
@Component({
    moduleId: module.id,
    selector: "SecondComponent",
    templateUrl: 'SecondComponent.component.html',
    styleUrls: ['SecondComponent.component.css'],
})
SecondComponent.Component.css

.ui-tree .ui-tree-container {
    background-color: white;
    color: black;
}

我在内部使用 .ui-tree-container 的两个组件中都创建了 p-tree。我希望我的 secondComponent 的树的背景应该是白色的,而对于所有其他地方的树的背景应该保持黑色。

4

3 回答 3

2

您可以将 CSS 封装在组件选择器中。

FirstComponent.component.css

FirstComponent .ui-tree .ui-tree-container {
    background-color: #252525;
    color: white;
}

SecondComponent.component.css

SecondComponent .ui-tree .ui-tree-container {
    background-color: white;
    color: black;
}

通过这种方式,它们不会相互影响模板。此外,您可以选择ViewEncapsulation.None两者都使用或不使用。

于 2018-04-17T10:24:29.997 回答
1

您也可以对 FirstComponent 使用 Default ViewEncapsulation,而是分别在您的 css 文件中使用 ::ng-deep 选择器。

第二组件

::ng-deep .ui-tree .ui-tree-container{
  background-color: white;
  color: black;
}

第一个组件

::ng-deep .ui-tree .ui-tree-container{
  background-color: #252525;
  color: white;
}
于 2018-04-17T10:28:05.997 回答
0

如果你想重用 CSS white 只自定义一些部分,你可以使用 scss 变量

步骤1

创建具有通用属性和默认颜色的 scss 文件

公共树.scss

$bgColor : white !default;
$color: black !default;

.ui-tree .ui-tree-container {
    background-color: $bgColor;
    color: $color;
}

第2步

在组件的 scss 文件中,根据需要修改变量的值并导入通用 scss 文件

组件1.scsss

$bgColor:  #252525; /* Override colors */
$color: white;
@import './commontree.scss';

组件2.scss

/* Use default colors */
@import './commontree.scss';

为此,您可以(并且可能应该)将视图封装保持为默认值ViewEncapsulation.Emulated

Stackblitz 演示

于 2018-04-17T12:07:28.360 回答