Home > OS >  Make Angular component stylesheet work with sub-components
Make Angular component stylesheet work with sub-components

Time:11-09

I'm relatively new to Angular, and I have a doubt about component stylesheets.

I have an Angular 12 app and created a component named my-component. The template of the component in question is something like this:

my-component.html

<div>
  ...some html...
  <some-other-angular-component></some-other-angular-component>
  ...some other html...
</div>

some-other-angular-component is another component, either from the app itself or a third party library.

Now, what I want to do in my-component is apply some CSS rules to the contents of some-other-angular-component. I know that the HTML it generates contains classes that I can target, so I tried to add this to my component CSS:

my-component.scss

.some-other-angular-component-inner-class {
  background-color: red;
}

However, this doesn't work, it appears that the component's CSS file only applies rules to the HTML defined directly in the component's template, not the HTML generated by sub-components.

Is there a way to make this work? I find myself having to add my CSS to the webapp's main style.scss file, even when I want to apply the rule only to the particular some-other-angular-component instance inside of my-component. It makes styling confusing and needlessly fragmented. Is this intended, or what am I missing?

CodePudding user response:

I think you may want to look into View Encapsulation.

@Component({
  selector: 'app-no-encapsulation',
  template: `
    <h2>None</h2>
    <div >No encapsulation</div>
  `,
  styles: ['h2, .none-message { color: red; }'],
  encapsulation: ViewEncapsulation.None,
})
export class NoEncapsulationComponent { }

These styles will be added to head and will be applicable to other components as well if style rule matches.

Please note, with this you are only enabling this behaviour for just this component. Chances of overlapping CSS rules is still there but is lot less in comparison to directly putting styles in style.css.

I will also suggest that you add .class or #id attribute in mark up to ensure that your rules don't overlap by default.

For example:

.my-component .rule-one {
}

It will ensure that my rules are only applied are on component that has this class applied on it.

  • Related