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 {
border:1px solid red;
}

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:


@Component({
selector: 'my-comp',
templateUrl: 'my-comp.component.html',
styles: [`my-comp.component.css`],
encapsulation: ViewEncapsulation.Emulated
})

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:


@Component({
selector: 'my-comp',
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:


@Component({
selector: 'my-comp',
templateUrl: 'my-comp.component.html',
styles: [`my-comp.component.css`],
encapsulation: ViewEncapsulation.None
})

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 5.9.2.002.