简体   繁体   中英

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.

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?

Real use case example: I can't use class="row" while styling a component-wide custom logical row if I am using bootstrap.

Look at this 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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