【问题标题】:How to style encapsulated child components in angular?如何以角度设置封装的子组件的样式?
【发布时间】:2021-06-28 17:54:46
【问题描述】:

如何在 Angular 中设置封装子组件的样式?

以下是启用视图封装的子组件和父组件。

** child

//template
<div class="child-container"> </div>

// class
@Component({
  selector: "app-child",
  templateUrl: "./child.component.html",
  styleUrls: ["./child.component.css"],
  encapsulation: ViewEncapsulation.ShadowDom
})
** parent

//template
<div class="parent-container"> </div>

// class
@Component({
  selector: "app-parent",
  templateUrl: "./parent.component.html",
  styleUrls: ["./parent.component.css"],
  encapsulation: ViewEncapsulation.ShadowDom
})

如何从父组件的样式表中选择 Child 组件内的特定类并更改其样式?

** parent

//template
<div class="parent-container">
<app-child></app-child>
 </div>

// class
@Component({
  selector: "app-parent",
  templateUrl: "./parent.component.html",
  styleUrls: ["./parent.component.css"],
  encapsulation: ViewEncapsulation.ShadowDom
})

//styles
app-child {
.child-container {
background colour: red;
}
}

目前,当我尝试从子组件中选择一个类时,我无法覆盖它的样式。请帮忙!

请记住,我用过的外壳需要 ViewEncapsulation.ShadowDom。所以我们必须牢记这一点。

【问题讨论】:

  • 目前,当我尝试从子组件中选择一个类时,我无法覆盖它的样式。请帮忙!

标签: javascript angular


【解决方案1】:

css 变量可以通过 shadow dom 访问。 所以在你的应用父组件scss中,你应该能够做类似的事情

--child-comp-background: red;

在您的应用子组件 scss 中,

background-color: var(--child-comp-background, white) //white is a default incase the variable isnt defined or passed down from the parent

【讨论】:

    【解决方案2】:

    你可以使用 :host-context() 来做到这一点

    :host-context(.parent-container) .child-container{
    ...style here
    }
    

    这里是演示:Demo

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 2017-12-29
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2017-03-15
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多