See also https://angular.io/docs/ts/latest/guide/component-styles.html
View encapsulation
To allow external styles to affect the content of components you can change view encapsulation (that's what prevents styles to "bleed into" components).
@Component({
selector: 'some-component',
template: '<div></div>',
styleUrls: [
'http://example.com/external.css',
'app/local.css'
],
encapsulation: ViewEncapsulation.None,
})
export class SomeComponent {}
View encapsulation fulfills a purpose. The better way is to add styles directly to the component they should affect.
ViewEncapsulation
is set per component and may come handy in some situations.
"shadow piercing"
You can also use shadow piercing CSS combinator ::ng-deep
(>>>
and /deep/
are deprecated) to build selectors that cross component boundaries like
:host ::ng-deep .ng-invalid {
border-bottom: solid 3px red;
}
which styles all tags with a class ng-invalid
in the current component or any descendant with a red underline no matter if encapsulation is None
or Emulated
. It depends on browser support whether /deep/
works with Native
(as far as I know this is not supported by any browser anymore).
Note
The shadow piercing CSS combinators are similar to the ones from the shadow DOM spec where they are deprecated since quite a while.
With the default ViewEncapsulation.Emulated
Angulars own /deep/
and ::shadow
implementation are used and they will work even when Chrome removes native support.
With ViewEncapsulation.Native
Angular uses Chromes shadow DOM CSS combinators (only Chrome supported them at all anyway AFAIK). If Chrome finally removes them, then they won't work in Angular as well (again ViewEncapsulation.Native
only).
Global styles
Styles added globally (index.html
) don't consider component boundaries. Such styles are not rewritten by Angular2 and ViewEncapsulation.Emulated
doesn't apply to them. Only if ViewEncapsulation.Native
is set and the browser has native shadow DOM support, then global styles can't bleed in.
See also this related issue https://github.com/angular/angular/issues/5390