1

How to force CSS of child component from parent using ::ng-deep or something?

I have parent component where I put child component:

....parent.component...
<app-likes></app-likes>
.....parent.component......

Not inside that likes component there is he following HTML:

<div class="mainDiv">
<div class="secondDiv"><i class="far fa-heart fa-3x"></i></div></div>

Now I want to set color of fa-heart class to white from parent parent.component.css.

How can I do that?

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
David
  • 4,332
  • 13
  • 54
  • 93

3 Answers3

2

You can do this way, in the css of the parent component:

parent.component.css:

:host ::ng-deep .fa-heart {
  color: red;
}

or

:host ::ng-deep app-likes .fa-heart {
  color: red;
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
0

Well I will go against the folks above and suggest that you don't do this.

If you consider the component an isolated building block in your app, you would consider it an advantage, that it looks the same in every place you use it. Using ::ng-deep to override this behaviour will cause you trouble in larger apps.

Angular promotes using @Inputs as the interface of passing data into the component. My suggestion is to use @Input to modify the view. Or, if in larger contexts you can use Dependency Injection to provide a token that specifies a theme for all children of a component.

<app-likes theme="white"></app-likes>

@Component({selector: 'app-likes'})
class AppLikesComponent {
  @Input() theme: string;

  @HostBinging("class") get themeBinding() {
     return 'theme--' + this.theme;
  }
}
kvetis
  • 6,682
  • 1
  • 28
  • 48
  • 2
    often times, when the component is not your own, or is a library, you have to use `::ng-deep`, in that case. – HDJEMAI Sep 01 '20 at 16:18
-1

You could set the ViewEncapsulation option in the parent component to remove the shadow DOM. This essentially allows the child component to use the selector definitions from the parent component.

Try the following

Parent component

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None        // <-- no shadow DOM
})
export class AppComponent  {
}

Parent CSS

.fa-heart {
  color: white;
}

Working example: Stackblitz

ruth
  • 29,535
  • 4
  • 30
  • 57