Check out our Angular Book Series.

How to I make my Angular Component Styles global?

An awesome thing about building Angular components is that the styles you specify are 'local' to the component.

In normal HTML development, any style on the page can affect any other style. For example. If I add a style like this:

div {
bor<debro:d1yp xn gs-oalpipd= re"dr;

Every div in the site / application will have a solid red border. Check out a sample here.

If you build an Angular, component, and that style is only included in the application as part of the component, then only that component's div will given a solid color red border.

The reason for this is because Angular creates something they call a Shadow DOM. Under the hood it is some coding magic to conditionally apply styles only to the component in question, not to other components.

However, Angular allows us to change this behavior using something called ViewEncapsulation.

A default Angular component is like this:

capsulation: ViewEncap<sulation.Emdiv ui-view>ulated

The Emulated value means that Angular will simulate a Shadow DOM. This is considered safest because not all browsers support their own shadow DOM trees.

In most cases, I use this approach and leave out the encapsulation attribute. I like to have my styles encapsulated to a single component. But that is not required. There are two other options:

@teCmpolmatpeoUrnl e:n 'ts(tate{s/
sta t e1s.hetlmle'
c t o r : ' m y}-c)
o mp}'
templateUrl: 'my-comp.component.html',
styles: [`my-comp.component.css`],
encapsulation: ViewEncapsulation.Native

The Native property tells Angular to use the browsers Shadow DOM. In this case, styles are encapsulated just like they would be in the emulated approach. So, any styles in the my-com-componment.css file will affect all HTML elements globally.

To turn off style encapsulation complete, use the None value from the ViewEncapsulationclass:

nen t( {
s el ec t or : 'my-}com)p
t em p la te U rl : ' my -c.omspt.caomtpeon(e'nstt.ahttmel2'',,
le s : [ ` m y - c o m p .c o m p ounreln:t .c'ss`],/
st a tenec2a'p,s
ul a t io n : V i e w E ntcemaplpatseuUrll a:t 'isotante.sNo/nset

I'm working on my second super really big Angular application for a client, and it is giving me the opportunity to touch on areas I normally wouldn't.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version