代码之家  ›  专栏  ›  技术社区  ›  Hacker

从主体构件角度替代子构件样式的正确方法

  •  2
  • Hacker  · 技术社区  · 6 年前

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

    2 回复  |  直到 6 年前
        1
  •  2
  •   ConnorsFan    6 年前

    如果对子组件代码有控制权,则可以定义 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 一个演示。


    否则,在通过角度提出替代方法之前,可以使用 ::ng-deep shadow-piercing descendant combinator 要从父CSS修改子组件样式,请执行以下操作:

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

    this stackblitz 一个演示。

        2
  •  0
  •   Eliseo    6 年前

    我的“方法”是使用视图封装。无,重要,并向子级添加类。 这个 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>
    
    推荐文章