【问题标题】:Right way to override child component style from host component angular从主机组件角度覆盖子组件样式的正确方法
【发布时间】:2019-06-17 03:17:57
【问题描述】:

从宿主组件覆盖子组件样式的正确方法是什么。我尝试使用encapsulation: ViewEncapsulation.None,但我需要在 style.sass 文件而不是主机组件中编写覆盖内容。 stackblitz应该是什么

【问题讨论】:

标签: angular angular2viewencapsulation


【解决方案1】:

如果你对子组件代码有控制权,你可以定义一个customStyle输入属性:

@Input() customStyle: {};
<div class="child-div" [ngStyle]="customStyle">I am the child</div>

并从父组件传递:

<app-child [customStyle]="style1"></app-child>
style1 = {
  backgroundColor: "red",
  height: "150px"
}

请参阅this stackblitz 以获取演示。


类似的技术可以允许将特定的样式属性传递给子组件:

@Input() backgroundColor: string;
<div class="child-div" [style.background-color]="backgroundColor">I am the child</div>

来自父组件:

<app-child backgroundColor="red"></app-child>

请参阅this stackblitz 以获取演示。


否则,在 Angular 提出替代方法之前,您可以使用 ::ng-deep shadow-piercing descendant combinator 从父 CSS 修改子组件样式:

:host ::ng-deep .parent .child-div {
  background-color: lime;
  height: 200px;
}

请参阅this stackblitz 以获取演示。

【讨论】:

  • 但我们不应该使用 ::ng-deep 权利,因为它将被弃用。
  • 你可以看到this question关于::ng-deep的弃用。我同意接受的答案:在 Angular 提出替代技术之前使用它。
  • 据我所知,您可以使用::ng-deep 或ViewEncapsulation.None(目前)。
  • 你能告诉我使用 viewEncapsulation.None 的正确方法吗?它的情况需要在styles.scss中写覆盖样式吗?
  • 您可以在“父级”中使用 encapsulation:ViewEncapsulation.None 并将 !important 添加到 .css,例如背景颜色:石灰!重要
【解决方案2】:

我的“方式”是使用 viewEncapsulation.None,重要的是给孩子添加类。 forked stackblitz's Connors

//The parent
.child1 .child-div {
  background-color: lime!important;
  height: 200px!important;
}

<div style="text-align: center;" class='parent'>Hi I am the app-root and I contain child-comp!
<app-child class="child1"></app-child>
<app-child ></app-child>
</div>

【讨论】:

    猜你喜欢
    • 2019-09-26
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2018-08-15
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多