1

in an Angular application I have a component with <ng-content></ng-content>. I added the scss rules for content that will be put inside the ng-content, but they are ignored. I tried to solve using :host, but it doesn't work.

https://stackblitz.com/edit/angular-ewqhzj

Wrapper component:

<app-embed>
   <p>Hello world!</p><h1 class="toBeColored">toBeColored</h1>
</app-embed>

Styles in embed component:

:host {
  border: 5px solid red;
 padding: 15px;
 display: block;
 .toBeColored {
   color: pink;
 }
}

The problem is that the pink color of 'toBeColored' string is not set

panagulis72
  • 2,129
  • 6
  • 31
  • 71

4 Answers4

3

Try this

:host ::ng-deep{
  border: 5px solid red;
  padding: 15px;
  display: block;
   .toBeColored {
    color: pink !important;
  }
}

and remove encapsulation statement and try ti build

encapsulation: ViewEncapsulation.Native
Santosh Shinde
  • 1,206
  • 10
  • 16
  • It seems to work, but when I build in AOT I get the following error on '/deep/': An unhandled exception occurred: expected selector – panagulis72 Nov 11 '19 at 12:37
  • You declare global all your css component where only `.toBeColored` need to be set global – Wandrille Nov 11 '19 at 13:53
1

You can't achieve that with a clean way.

A workaround would be to create global css :

:host {
 ...;
 ::ng-deep .toBeColored {
   color: pink;
 }
}

But it will be deprecated. See this issue

::ng-deep is going to hold the web record for long-lived deprecated API.

Wandrille
  • 6,267
  • 3
  • 20
  • 43
1

Try adding encapsulation: ViewEncapsulation.Native to your embed component like

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-embed',
  templateUrl: './embed.component.html',
  styleUrls: ['./embed.component.scss'],
  encapsulation: ViewEncapsulation.Native
})
export class EmbedComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
1

You should be able to apply the styles in the parent component that projects the content into the ng-content tag. The angular styles isolation appears to consider the content to be part of the component where the HTML is declared.

https://stackblitz.com/edit/angular-ivy-q9dn68

Mark
  • 3,459
  • 1
  • 18
  • 23