How to style template inside the component

2.1k Views Asked by At

So, I want to pass a template to the component and render this template inside with style applied from this component, not from the calling component. Is it any way to do this without setting ViewEncapsulation.None?

I made a small stackblitz for that. I want param button also rendered green.

https://stackblitz.com/edit/angular-zrpufe?file=src%2Fapp%2Fhello.component.ts

2

There are 2 best solutions below

1
talhature On

Just try this one

  styles: [`
   ::ng-deep button {
       background: green;
    }
  `]

Use the ::ng-deep shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The ::ng-deep combinator works to any depth of nested components, and it applies to both the view children and content children of the component.

EDIT: This deep selector has been deprecated for a long time and CSS Work Group has not agreed on an alternative yet. Untill there is a replacement I favor to use deep, because, while alternative solutions like wrapping the element with a div and styling globally is good to go, it has problems too, the biggest issue with it, it doesnt work inter-modules in angular. It is up to you to decide.

3
Marian Simonca On

I do not recommend using ::ng-deep at all. It is deprecated and in time will be removed for good.

Check this answer.

I changed your code and added a container div for your HelloComponent. With a class on that div you can control the styles inside your component. Any style that you write like that in your main style.css file won't need ::ng-deep or ViewEncapsulation.None.

// styles.scss 

  .hello-container button {
      background: green;
   }
// hello.component.ts -> template

<div class="hello-container">
 ...
</div>

OR

even simpler:

You do not need the container div, just add this in your style.css

hello button {
      background: green;
    }

'hello' is the selector for your component and it will apply that style to EVERY button in your component.