7

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

1
  • I have tried to use encopsulation also Commented Dec 2, 2019 at 19:43

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

When using ::ng-deep, I'll suggest wrapping in in ::host selector to avoid unintended outcomes.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.