-2

I am working on a angular 11.2 project and I see that CSS of a component is getting applied to another component which has the same css selector name. How can I stop this? please help

sps
  • 25
  • 7

3 Answers3

2

If you apply the styles in Angular @component, it should be applied to that component scope only.

https://angular.io/guide/component-styles

@Component({
  selector: 'app-root',
  template: `
    <h1>Tour of Heroes</h1>
    <app-hero-main [hero]="hero"></app-hero-main>
  `,
  styles: ['h1 { font-weight: normal; }']
})
export class HeroAppComponent {
/* . . . */
}
Jkarttunen
  • 6,764
  • 4
  • 27
  • 29
0

Use encapsulation in your component declaretion

@Component({

selector:'app-component',

templateUrl:'app.compionent.html',

encapsulation:ViewEncapsulation.None,

})
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
  • I guess that you want to say : ´encapsulation:ViewEncapsulation.Emulated´: `None` means that Angular does no view encapsulation. Angular adds the CSS to the global styles, so a CSS selector name rule will be applied to another component which has the same css selector name. `Emulated` option (the default) emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view – Juan Vicente Berzosa Tejero Jun 27 '21 at 10:18
  • Yes I tried this but after doing this, I am not able to target the library css classes. How to I use emulated but still be able to target the 3rd party library component's css classes? – sps Jun 27 '21 at 14:18
0

My solution was to use ViewEncapsulation.None but to use targeted css. ie using specificity. for example if i had a component structure as below:

<div class="parent">
  <div class="child">
    <span></span>
  </div>
</div>

My css would be :

.parent .child > span { ...some css here}

The reason not to use Emulated is that, some lib components can't be targeted with "None" as ViewEncapsulation. hence we need to set it to None and then follow this approach.

sps
  • 25
  • 7