Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override CSS styles of component in Angular?

I have a custom component <app-button><span></span></app-button>.

It has CSS styles like:

span:hover {
   color: red;
}

When I use this component in another and tried to apply CSS styles in parent component it has not effect:

<app>
<app-button></app-button>
</app>

Inside app component I have tried:

  app-button span:hover {
       color: green;
    }

It does not work for me

like image 504
OPV Avatar asked Dec 02 '19 19:12

OPV


People also ask

How do I overwrite angular materials in CSS?

Our solution to ViewEncapsulation was to override very specific css using highly specific css selectors in 1) global css or 2) creating separate style files for certain views / styles / elements, importing into every component required (e.g. styleUrls: [material-table-override.

How do I override SCSS style?

Overriding the Base Styles scss . In order to override a base style file, you need to copy over the chain of files that is used to import it.


1 Answers

you could use the ng-deep selector:

::ng-deep app-button span:hover {
   color: green;
}

which will make your styles penetrate to child components. but this functionality is due to be deprecated soon according to the angular team, and people are advised to get off of it. (PERSONAL opinion: too many projects rely on ng-deep for them to deprecate it anytime soon)

the best way to do it currently IMO is with a global style sheet with something like:

app app-button span:hover {
   color: green;
}

you also could set the view encapsulation to none on your parent component, but that's functionally similar to a global style sheet, and can be confusing if you don't set things up correctly and forget where / why you put global styles that only load when a component loads, and leads to some bugs in my experience.

like image 62
bryan60 Avatar answered Sep 30 '22 09:09

bryan60