How to stop css bleeding in angular 11.2

887 Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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.

2
On

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 {
/* . . . */
}
2
On

Use encapsulation in your component declaretion

@Component({

selector:'app-component',

templateUrl:'app.compionent.html',

encapsulation:ViewEncapsulation.None,

})