简体   繁体   English

如何防止全局CSS选择器干扰Angular(6)中的隔离组件?

[英]How to prevent global css selectors to interfere with isolated components in Angular (6)?

Even if your component stylesheet will be applied in isolation to its component only (eg while using the default ViewEncapsulation.Emulated ) the class names you will use on your template will still clash with any existent global styling, so you cannot really use more than one single class namespace. 即使您将组件样式表仅单独应用于其组件(例如,使用默认的ViewEncapsulation.Emulated ),您将在模板上使用的类名仍会与任何现有的全局样式发生冲突,因此您实际上不能使用多个单类名称空间。

This can lead to always prefixing class names, which in turn can result in very long, weird name groups. 这可能导致始终为类名加上前缀,从而导致名称组很长,很奇怪。

Is there any best practice out there to keep your class names brief and clean (ideally 1-word) without any risk of clashing with any global styling that might be in place? 是否有最佳实践来保持您的班级名称简洁明了(理想情况下为1个字),而又不会与任何可能存在的全局样式冲突?

Real use case example: I can't use class="row" while styling a component-wide custom logical row if I am using bootstrap. 实际用例示例:如果我使用引导程序,则在样式组件级自定义逻辑行时不能使用class="row"

Look at this StackBlitz . 看看这个StackBlitz I want the header of my a component to be fixed-width and bordered only, but it ends up to also have a red background because of global styling. 我想我的头a组件是固定的宽度只有接壤,但它最终也有由于全球造型的红色背景。

Yes. 是。 I can use a different word, but I should always be aware of the entire word set that is currently used by global styling, not to mention that I don't know whether more global styles will be added in the future, especially in large applications. 我可以使用其他单词,但是我应该始终了解全局样式当前使用的整个单词集,更不用说我不知道​​将来是否会添加更多的全局样式,特别是在大型应用程序中。

Changing your view encapsulation to native will make Angular use native shadow DOM and avoid the clash of the global style 将视图封装更改为本机封装将使Angular使用本机阴影DOM并避免全局样式的冲突

@Component({
  selector: 'app-a',
  templateUrl: './a.component.html',
  styleUrls: ['./a.component.css'],
  encapsulation:  ViewEncapsulation.Native
})

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

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