1

I have a Parent component parent.html and it has CSS styles like below

.style1{
color:red
}
.style2{
color:red
}

and I'm reusing this component in child.html. Now I want to override the parent component styles in child component. I try to use ::ng-deep it is working but if load Parent component, what are the styles overrides in child component it is reflecting in parent component also..

I want to override only styles in child component but should not reflect in parent component. How we can do this?

2 Answers 2

4

For this you need to use encapsulation: ViewEncapsulation.None in parent and then you will be able to add the override by adding more specific selector like in child component -

child-component .style1{
   color:red
}

child-component .style2{
   color:red
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can you give some live examples in this?
I'm using this parent component in router-outletif I use encapsulation: ViewEncapsulation.None then it is not taking other styles. here I want override only selected styles not all the styles
You can leverage ngStyle and Input to override the specific property. Demo link is updated as well. Please check same link.
It is not accepting if I write style class, if I write inline style it is accepting
0

I think you must be having two components with 2 seperate directory and it should have html, ts, css files.

So in parent component's html you will reference child component -
parent.component.html -> <app-child> </app-child>

In the child component you should have - child.component.html, child.component.ts, child.component.css files.
If you create and add any similar styles like parent.component.css file in child.component.css then those will get added to each component like p[random_atttr_value], so now you will have seperate styles for p in child.

This is default behaviour of angular, comes in view encapsulation. Used by angular like shadow DOM techonlogy which is not supported by all broswers but angular does it like this.
In other words it adds some attributes to each component rendered on browser.
ViewEncapsulation has 3 options -

encapsulation: ViewEncapsulation.None, 
           ViewEncapsulation.Emulated, (-- this is default)
           ViewEncapsulation.Native (-- only applies to browsers with shadow DOM technology)<br>

Hope this will help you to solve your problem.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.