ram12393
ram12393

Reputation: 1258

Override Parent component styles in child component

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?

Upvotes: 1

Views: 10876

Answers (2)

Durgesh
Durgesh

Reputation: 205

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.

Upvotes: 0

Sunil
Sunil

Reputation: 11243

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
}

Upvotes: 4

Related Questions