'How do I style an Angular component's nested CSS class?
Let's say I have a simple Angular component here called MyComponent.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: '[my-component]',
template: `
<div class="my-component-child">
<ng-content></ng-content>
</div>`,
encapsulation: ViewEncapsulation.None,
host: { 'class': 'my-component' }
})
export class MyComponent {
constructor() { }
}
This component is then used inside ParentComponent.
Because MyComponent encapsulation is set to none, I can style its .my-component class from within ParentComponent but I cannot style .my-component-child unless I set ParentComponent encapsulation to none, which I prefer to avoid.
How can I style .my-component-child or workaround it (without using root styles.scss or ::ng-deep or parent's encapsulation set to none)?
If it's not possible to do the above with those conditions, are there any Angular practices or strategies that deal with this kind of situation (I'm still fairly new to Angular)?
Solution 1:[1]
A solution is to pass CSS classes to the child component. Your component will look like this:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: '[my-component]',
template: `
<div class="my-component-child" [ngClass]="extraClasses">
<ng-content></ng-content>
</div>`,
encapsulation: ViewEncapsulation.None,
host: { 'class': 'my-component' }
})
export class MyComponent {
constructor() { }
@Input() extraClasses = ""
}
Then pass in extra classes to the child:
<my-component [extraClasses]="flex"></my-component>
Of course, in this structure, you need to define the classes in the global context.
If you still don't want to declare any classes globally, then the other approach is to pass your desired options to the child and let the child component style itself based on the given options.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hamidreza Vakilian |
