0

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

s-f
  • 2,091
  • 22
  • 28

2 Answers2

2

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.

Marian Simonca
  • 1,472
  • 1
  • 16
  • 29
  • 1
    thanks for the notice, yes it has been deprecated for a long time and also CSS WG has not agreed on an alternative yet it could take years and there are too many objections about that deprecation, Using global custom style sheets also may not be the best call. – talhature May 07 '19 at 10:35
  • 1
    Agreed. Both solutions work, but in the end, I personally prefer not to use ng-deep. Cheers :) – Marian Simonca May 07 '19 at 10:39
  • yeah, I was thiking about global styles, but maybe there's solution without them. a bit of context, this problem comes from the library project, so I would have to deliver global styles to the host app as well. – s-f May 07 '19 at 10:55
1

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.

talhature
  • 2,246
  • 1
  • 14
  • 28