How to Apply css on child components in Angular
Parent Components and child components
So, starting from the beginning if we have to add css on any component element. We can put it directly in the component css. But when we want to apply css to child component and we place that in component css. You will notice no css is getting applied to child component. The main issue about this is that the scope of component css is limited to the component itself . So we will see how to make it work on child components.
Old way- previously we could have applied css on child components using the ::ng-deep
shadow-piercing descendant combinator for that.
:host(.test) ::ng-deep div.label {
border: 1px solid red;
}
:host(.test) ::ng-deep div.value {
border: 1px solid green;
}
But now a days this has been deprecated so this is not used anymore. So we will see how to do it other way
ViewEncapsulation.None
So, View Encapsulation in Angular is a strategy which we use that determines how angular hides (encapsulates) the styles defined in the component from reaching to the the other parts or componetns of the application. The following three strategies provided by the Angular to determine how styles are applied. So, we can use ViewEncapsulation.None on the parent component like you can check in this code sample
@Component({ selector: 'app-log', templateUrl: './log.component.html', styleUrls: ['./log.component.css'], encapsulation: ViewEncapsulation.None })
This, will allow the parent components css to be applied on the child components. After you add this on your component, you have to stop the project and run again and you will notice you css has been applied on child components.
So, this is how we can apply css on child components in Angular js.