POV
POV

Reputation: 12005

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

Upvotes: 7

Views: 24290

Answers (2)

bryan60
bryan60

Reputation: 29335

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.

Upvotes: 17

German Quinteros
German Quinteros

Reputation: 1930

In addition to ng-deep as they showed you in the other answer: https://stackoverflow.com/a/59145690/12171299

You can set an @Input() where you define the color of span element like this:

<app>
  <app-button [spanColor]="'red'"></app-button>
</app>

Then in your AppButtonComponent:

export class AppButtonComponent implements AfterViewInit {
   public spanStyle = {};
   @Input() public spanColor: string;

   public ngAfterViewInit(): void {
    if (spanColor) {
      this.spanStyle = {
        'color': `${spanColor}`
      };
    }
  }
}

Finally, in the AppButtonComponent html you have to do:

<span [ngStyle]="spanStyle"></span>

With this approach, you can avoid using ng-deep and removing the Style Encapsulation of a Component.

Upvotes: 1

Related Questions