Right way to override child component style from host component angular

后端 未结 2 1275
忘掉有多难
忘掉有多难 2020-12-11 04:30

What is the right way to override child component style from host component. I tried using encapsulation: ViewEncapsulation.None but i need to write the overri

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 05:10

    If you have control on the child component code, you can define a customStyle input property:

    @Input() customStyle: {};
    
    I am the child

    and pass it from the parent component:

    
    
    style1 = {
      backgroundColor: "red",
      height: "150px"
    }
    

    See this stackblitz for a demo.


    A similar technique can allow to pass a specific style attribute to the child component:

    @Input() backgroundColor: string;
    
    I am the child

    from the parent component:

    
    

    See this stackblitz for a demo.


    Otherwise, until an alternative method is proposed by Angular, you can use the ::ng-deep shadow-piercing descendant combinator to modify the child component styling from the parent CSS:

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

    See this stackblitz for a demo.

提交回复
热议问题