Sunday, December 10, 2017

Global CSS Styles in Angular

Angular recommends component based styling as the component should encapsulate every UI functionality. Here is a typical example using stylesheet for a component:

import { Component } from "@angular/core";

@Component({
    selector: "top-bar",
    templateUrl: "./TopBarComponent.html",
    styleUrls: ["./TopBarComponent.css"]
})
export class TopBarComponent {
}

In some situations we may need to have styles that we want to apply to multiple components or globally across the entire application. In this case we can define a css file and use it in the index.html page.

<link rel="stylesheet" href="~/styles.css" />

With the above approach we may lose the building and bundling provided by Angular and have to extend or implement a separate webpack or gulp task.
I recommend creating a separate component which contains all the global styles and expose these component’s style using encapsulation as shown below:

import { Component, ViewEncapsulation } from "@angular/core";

@Component({
    selector: "app-styles",
    template: "",
    styleUrls: ["./AppStyles.css"],
    encapsulation: ViewEncapsulation.None
})
export class AppStyles {
}

ViewEncapsulation.None exposes all the styles defined in AppStyles.css globally and these styles can be across the application. As a final step we need to include this AppStyles Component (which does not have any visible elments) inside our AppComponent


<app-styles></app-styles>