简体   繁体   English

如何在 Angular 11.2 中阻止 css 流血

[英]How to stop css bleeding in angular 11.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.我正在处理一个 angular 11.2 项目,我看到一个组件的 CSS 正在应用到另一个具有相同 css 选择器名称的组件。 How can I stop this?我怎么能阻止这个? please help请帮忙

If you apply the styles in Angular @component, it should be applied to that component scope only.如果您在 Angular @component 中应用样式,它应该只应用于该组件范围。

https://angular.io/guide/component-styles 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 {
/* . . . */
}

Use encapsulation in your component declaretion在组件声明中使用encapsulation

@Component({

selector:'app-component',

templateUrl:'app.compionent.html',

encapsulation:ViewEncapsulation.None,

})

My solution was to use ViewEncapsulation.None but to use targeted css.我的解决方案是使用 ViewEncapsulation.None 但使用目标 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 :我的 css 将是:

.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.不使用 Emulated 的原因是,某些 lib 组件不能使用“None”作为 ViewEncapsulation。 hence we need to set it to None and then follow this approach.因此我们需要将其设置为 None 然后遵循这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM